import * as types from './mutation-types'
import * as gtypes from '../../mutation-types'
import webchat from '../../api/webchat'
import customer from '../../api/customer'
import config from '../../api/config'
import { Message } from 'element-ui'
import { formatShortTime, getFormatDateTime, m7Language, getCache, deepClone, Base64 } from '@/utils/m7Utils.js'
import { renderEmoji, msgConvertion, userStayTimeConverse } from '@/utils/webchat.js'
import { Player } from '../../../components/business-modules/webchat/trackVideo/recorder'
import Vue from 'vue'
import * as monitotTypes from '../monitor/mutation-types'
import md5 from 'md5'
import m7dicMap from '@utils/m7dicMap'
let trackVideoStore = {}

export const updateWebchatAutoClaimStatus = ({ commit }, data) => {
  return new Promise(function (resolve) {
    webchat.updateWebchatAutoClaimStatus(data)
      .then(
        response => {
          if (response.success) {
            commit(types.SET_WEBCHAT_AUTOCLAIM, data)
            resolve(response)
          } else {
            // 切换web领取开关时由于socket已断开导致提示服务异常的处理，提示客户重新登录生效
            if (response.message === 'im_socket_disconnected') {
              commit(gtypes.SET_ERROR, 'message.webSocketSwitchFailTip')
            } else if (response.message === 'chatStatusDetail_not_enable') {
              commit(gtypes.SET_ERROR, 'message.chatStatusDetail_not_enable')
            } else {
              commit(gtypes.SET_ERROR, 'message.default_tips')
            }
            resolve(response)
          }
        }
      ).catch((err) => {
        console.log(err)
        // 'message.default_tips'
      })
  })
}
/**
 * 获取当前座席的待处理数和所在技能组下的待领取数
 */
export const refreshWebchatMenuNum = ({ commit }) => {
  webchat.refreshMenuNum().then(response => {
    if (response.success) {
      let obj = {
        undealNum: response.openNum,
        todoNum: response.todoNum
      }
      commit(types.SET_WEBCHAT_UNDEALNUM, obj)
    }
  }).catch(err => {
    console.log(err)
    commit(gtypes.SET_ERROR, err)
  })
}
export const getUndealInvitation = ({ commit, dispatch }) => {
  return webchat.getUndealInvitation({}).then(response => {
    if (response.success) {
      response.data.forEach((obj) => {
        commit(types.CHANGE_INVITE_NOTIFY, {
          userName: obj.userName,
          sessionId: obj._id,
          sid: obj.sid,
          toPeer: obj.toPeer
        })
        console.log('userName:' + obj.userName + '  sessionId:' + obj._id + ' sid:' + obj.sid + ' toPeer:' + obj.toPeer)
        dispatch('changeInvite', {
          userName: obj.username,
          sessionId: obj._id,
          sid: obj.sid,
          toPeer: obj.toPeer,
          todo: 'add',
          type: 'beInvited'
        })
      })
    }
  }).catch(err => {
    console.log(err)
    commit(gtypes.SET_ERROR, err)
  })
}
/**
 * 查询处理中或全部IM会话数据真实count
 */
export const queryWebchatListCount = ({ commit, state }, data) => {
  return webchat.queryWebchatSession(data)
    .then(response => {
      return response
    }).catch(err => {
      console.log(err)
      // 'message.default_tips'
    })
}
/**
 * 查询处理中或全部IM会话数据
 */
export const queryWebchatList = ({ commit, state }, data) => {
  let submenu = data.submenu
  let searchAllCount = data.searchAllCount
  delete data.searchAllCount
  return webchat.queryWebchatSession(data)
    .then(response => {
      if (!searchAllCount) { // 不是查询总数的请求时
        commit(types.QUERY_WEBCHAT_LIST, { webchatList: response, submenu })
        commit(types.SORTLISTBY_TYPE)
      }
      if (submenu === 'webchat_todo') {
        response.list.forEach((data) => {
          if (!data.isAgentLastReply) {
            webchatHourMeter({ commit, state }, {
              startWaitTimer: data.startWaitTimer,
              online: data.userStatus,
              sessionId: data._id
            })
          }
        })
        commit(types.SORTLISTBY_TYPE)
      }
      return response
    }).catch(err => {
      console.log(err)
      // 'message.default_tips'
    })
}
/**
 * 查询机器人会话列表
 */
export const queryWebchatSessionByStatus = ({ commit, state }, data) => {
  let submenu = data.submenu
  let searchAllCount = data.searchAllCount
  delete data.searchAllCount
  delete data.submenu
  return webchat.queryWebchatSessionByStatus(data)
    .then(response => {
      if (!searchAllCount) { // 不是查询总数的请求时
        commit(types.QUERY_ROBOT_LIST, { webchatList: response, submenu })
      }
      return response
    }).catch(err => {
      console.log(err)
      // 'message.default_tips'
    })
}

// 领取机器人会话
export const robotclaimSession = ({ commit }, data) => {
  return webchat.robotclaimSession(data)
    .then(response => {
      if (response.success) {
        commit(gtypes.SET_SUCCESS, 'webchat.robotClaimSuccess')
        return response
      }
    }
    ).catch(() => {
    })
}

// 领取排队会话
export const queueclaimSession = ({ commit }, data) => {
  return webchat.queueclaimSession(data)
    .then(response => {
      if (response.success) {
        commit(gtypes.SET_SUCCESS, 'webchat.robotClaimSuccess')
        return response
      }
    }
    ).catch(() => {
    })
}

/**
 * 导出全部中有处理类型的会话
 */
export const exportWebchat = ({ commit, state }, data) => {
  return webchat.exportWebchat(data)
    .then(response => {
      if (response.success) {
        commit(gtypes.SET_FILEDOWNLOAD, { path: response.path, isSession: true })
      } else {
      }
    }).catch(err => {
      console.log(err)
      // 'message.default_tips'
    })
}

/**
 * 导出全部中有处理类型的会话的内容
 */
export const exportWebchatContent = ({ commit, state }, data) => {
  return webchat.exportWebchatContent(data)
    .then(response => {
      if (response.success) {
        commit(gtypes.SET_SUCCESS, 'message.export_webchat_content_success')
      } else {
        if (response && response.message.indexOf('export_task_max_limit') > -1) {
          commit(gtypes.SET_ERROR, 'message.export_task_max_limit')
        } else {
          commit(gtypes.SET_ERROR, 'message.default_tips')
        }
      }
    }).catch(err => {
      console.log(err)
    })
}
/**
 * 根据id查询客户名称和创建时间数据
 */
export const popupWebchatById = ({ commit }, data) => {
  delete data.submenu
  return webchat.popupWebchat(data)
    .then(response => {
      return response
    }).catch(err => {
      console.log(err)
      // 'message.default_tips'
    })
}
/**
 * 获取当前会话详细信息
 */
export const popupWebchat = ({ commit, state, rootState, dispatch }, data) => {
  let submenu = data.submenu
  let eventLogData = {
    _id: data._id,
    sid: data.sid,
    timeStart: new Date().getTime(),
    apiType: 'popupWebchat',
    type: 'requestTimeout',
    submenu: data.submenu
  }
  delete data.submenu
  return webchat.popupWebchat(data)
    .then(response => {
      let webchatSession = response.user
      let customer = {}
      if (response.row) {
        webchatSession.custId = response.row._id
        customer = response.row || {}
      }
      if (webchatSession.invitedUserName && webchatSession.inviteUserStatus === 'accept') {
        webchatSession.shwoInviteBtn = false
        webchatSession.assistAgent = true
        // inviteCon 邀请座席的信息
        webchatSession.inviteCon = false
        webchatSession.inviteConData = {}
      } else {
        if (webchatSession.invitedUserName && webchatSession.inviteUserStatus === 'undeal') {
          commit(types.CHANGE_INVITE_NOTIFY, {
            userName: webchatSession.invitedUserName,
            sessionId: webchatSession._id,
            sid: webchatSession.sid,
            toPeer: ''
          })
          webchatSession.inviteCon = true
          webchatSession.inviteConData = {
            userName: webchatSession.invitedUserName,
            sessionId: webchatSession._id,
            sid: webchatSession.sid
          }
        }
        webchatSession.shwoInviteBtn = true
      }
      webchatSession.username = ''
      if (getCache('agents', webchatSession.user) && getCache('agents', webchatSession.user).displayName) {
        webchatSession.username = getCache('agents', webchatSession.user).displayName
      }
      commit(types.POPUP_WEBCHAT_INFO, { session: webchatSession, submenu })
      commit(gtypes.SET_CURRENT_CUSTOMER, { data: customer, type: 'webchat', tabType: submenu, businessId: data._id })
      if (response && response.success) {
        eventLogData.endTime = new Date().getTime()
        eventLogData.time = eventLogData.endTime - eventLogData.timeStart
        let account = rootState.session.account.account
        if (((eventLogData.endTime - eventLogData.timeStart) > 2000) && account === 'N00000000011') {
          dispatch('collectEventLog', eventLogData)
        }
      }
    }).catch(err => {
      console.log(err)
      // 'message.default_tips'
    })
}
/**
 * 查询聊天记录内容：
 * @param {String} data.sessionId 会话Id
 * @param {String} data.sid 访客id，必传
 * @param {String} data.when 时间戳字段，后端按此时间往前查找
 * @param {String} data.limit 消息条数
 * @param {Boolean} data.whenGt 查询方向，为true即为从此时间戳往现在查，用于断线重连后自动加载，不传就是正常往以前查询
 */
export const queryMessageHistory = ({ commit, state, rootState }, data) => {
  let submenu = data.submenu
  let whenGt = data.whenGt
  let isNew = data.isNew
  let currentSessionId = data.currentSessionId
  let arr = []
  // delete data.whenGt
  delete data.submenu
  delete data.isNew
  delete data.currentSessionId
  return new Promise((resolve) => {
    webchat.queryMessageHistory(data)
      .then(response => {
        if (response.list) {
          arr = response.list.reverse()
          let userSessionId = rootState.session.sessionId
          arr.forEach((item, index) => {
            let uid = item.user
            let type = item.type // in, out
            if (type === 'out') {
              let user = { displayName: m7Language('public.myselfI') }
              if (uid !== '' && uid !== userSessionId) {
                user = getCache('agents', uid) || { displayName: 'NA' }
              }
              item.uidDesc = user.displayName
              if (uid === 'system') {
                item.uidDesc = m7Language('public.system')
              }
              if (uid === 'robot') {
                item.uidDesc = m7Language('public.robot')
                item.robot = true
              }
            }
          })
          let run = (arr, i) => {
            return new Promise((resolve) => {
              let item = arr[i]
              if (item) {
                let isEsc = false
                let msgType = item.contentType
                if (msgType === 'text') {
                  if (item.showHtml === true || item.showHtml === 'true') {
                    isEsc = true
                  }
                } else if (msgType === 'image') {
                  isEsc = true
                } else if (msgType === 'file') {
                  // item.fileName = transferFileContent(item.message)
                  if (item.platform === 'wxkf') {
                    item.fileName = transferWxkfFileContent(item.message)
                  } else {
                    item.fileName = transferFileContent(item.message)
                  }
                  Vue.set(item, 'mp3Suffix', checkSuffix(item.fileName, 'mp3,wav,ogg'))
                  if (item.mp3Suffix) {
                    Vue.set(item, 'play', false)
                  }
                  isEsc = true
                } else if (msgType === 'voice') {
                  Vue.set(item, 'play', false)
                } else if (msgType === 'NewPushQues' && (item.showHtml === true || item.showHtml === 'true')) {
                  isEsc = true
                }
                item.message = renderEmoji(item.message, isEsc, item.contentHasUrl)
                if (msgType === 'text') {
                  item.contentHasUrl = ''
                  let oldContent = item.message
                  let contentNew = msgConvertion(item.message)
                  item.message = contentNew
                  if (oldContent !== contentNew) {
                    isEsc = true
                    item.contentHasUrl = 'have'
                  }
                }
                if (item.dateTime) {
                  item.showTime = item.dateTime
                }
                let currentCustomer = state.current[submenu].currentCustomer || {}
                if (item.contentType === 'text' && item.user !== 'system' && item.user !== 'robot' && !currentCustomer._id) {
                  autoMatchMsg({ commit, state }, {
                    message: item.message,
                    sessionId: currentSessionId,
                    flag: 'new'
                  }).then(() => {
                    resolve()
                  })
                } else {
                  resolve()
                }
              } else {
                resolve()
              }
            }).then(() => {
              if (i < arr.length - 1) {
                run(arr, i + 1)
              } else {
                resolve()
              }
            })
          }
          run(arr, 0)
        }
      })
  }).then(() => {
    if (submenu === 'qualityCheck') {
      commit(types.QUALITY_QUERY_WEBCHAT_HISTORY, {
        page: data.page,
        historyList: arr,
        sessionId: data.sessionId,
        submenu: submenu
      })
    } else if (whenGt) {
      commit(types.PROCESS_OFFLINE_MSG, {
        historyList: arr,
        sessionId: currentSessionId,
        submenu: submenu,
        whenGt: whenGt
      })
    } else {
      commit(types.QUERY_WEBCHAT_HISTORY, {
        historyList: arr,
        submenu: submenu,
        sessionId: currentSessionId,
        isCurrentSession: data.sessionId === currentSessionId,
        isNew: isNew
      })
    }
    return arr
  }).catch(err => {
    console.log(err)
    // 'message.default_tips'
  })
}
/**
 * 根据id查询会话数据
 */
export const queryChatInformationById = ({ commit }, data) => {
  delete data.submenu
  return webchat.queryChatInfoById(data)
    .then(response => {
      return response
    }).catch(err => {
      console.log(err)
      // 'message.default_tips'
    })
}
/**
 * 根据id获取历史记录
 */
export const queryUserContactHistory = ({ commit, rootState, state }, data) => {
  let arr = []
  delete data.submenu
  return webchat.queryUserHistory(data)
    .then(response => {
      if (response.list) {
        if (!data.showFirstWord) {
          arr = response.list.reverse()
        } else {
          arr = response.list
        }
        let userSessionId = rootState.session.sessionId
        arr.forEach((item, index) => {
          let uid = item.user
          let type = item.type // in, out
          if (type === 'out') {
            let user = { displayName: m7Language('public.myselfI') }
            if (uid !== '' && uid !== userSessionId) {
              user = getCache('agents', uid) || { displayName: 'NA' }
            }
            item.uidDesc = user.displayName
            if (uid === 'system') {
              item.uidDesc = m7Language('public.system')
            }
            if (uid === 'robot') {
              item.uidDesc = m7Language('public.robot')
              item.robot = true
            }
          }
          if (item) {
            let isEsc = false
            let msgType = item.contentType
            if (msgType === 'text') {
              if (item.showHtml === true || item.showHtml === 'true') {
                isEsc = true
              }
            } else if (msgType === 'image') {
              isEsc = true
            } else if (msgType === 'file') {
              // item.fileName = transferFileContent(item.message)
              if (item.platform === 'wxkf') {
                item.fileName = transferWxkfFileContent(item.message)
              } else {
                item.fileName = transferFileContent(item.message)
              }
              Vue.set(item, 'mp3Suffix', checkSuffix(item.fileName, 'mp3,wav,ogg'))
              if (item.mp3Suffix) {
                Vue.set(item, 'play', false)
              }
              isEsc = true
            } else if (msgType === 'voice') {
              Vue.set(item, 'play', false)
            } else if (msgType === 'NewPushQues' && (item.showHtml === true || item.showHtml === 'true')) {
              isEsc = true
            }
            item.message = renderEmoji(item.message, isEsc, item.contentHasUrl)
            if (msgType === 'text') {
              item.contentHasUrl = ''
              let oldContent = item.message
              let contentNew = msgConvertion(item.message)
              item.message = contentNew
              if (oldContent !== contentNew) {
                isEsc = true
                item.contentHasUrl = 'have'
              }
            }
            item.showTime = item.dateTime
          }
        })
      }
      return response
    }).catch(err => {
      console.log(err)
      // 'message.default_tips'
    })
}
/**
 * 根据id查询会话数据
 */
export const queryChatInfoById = ({ commit, state, rootState, dispatch }, data) => {
  let submenu = data.submenu
  if (submenu === 'webchat_todo') {
    data.queryHistory = true
  }
  let eventLogData = {
    _id: data._id,
    sid: data.sid,
    timeStart: new Date().getTime(),
    apiType: 'queryChatInfoById',
    type: 'requestTimeout',
    submenu: submenu
  }
  delete data.submenu
  return webchat.queryChatInfoById(data)
    .then(response => {
      if (Object.keys(data).length === 1 && data._id) {
        return response
      } else {
        let sessionFormHistory = []
        if (response.sessionFormHistory) {
          sessionFormHistory = response.sessionFormHistory.reverse()
        }
        commit(types.QUERY_WEBCHAT_INFO_BY_ID, {
          chatInfoById: response.chatSession,
          visitInfoList: response.historyList || [],
          sessionFormHistory: sessionFormHistory,
          submenu
        })
        if (response && response.success) {
          eventLogData.endTime = new Date().getTime()
          eventLogData.time = eventLogData.endTime - eventLogData.timeStart
          let account = rootState.session.account.account
          if (((eventLogData.endTime - eventLogData.timeStart) > 2000) && account === 'N00000000011') {
            dispatch('collectEventLog', eventLogData)
          }
        }
        return response
      }
    }).catch(err => {
      console.log(err)
      // 'message.default_tips'
    })
}
/**
 * 查询当前座席信息
 */
export const getCurrentUser = ({ commit, dispatch }, data) => {
  return config.getCurrentUser(data)
    .then(response => {
      let max = parseInt(response.user.maxImDealCount)
      let min = parseInt(response.user.minImDealCount)
      let imDealCount = parseInt(response.user.imDealCount)
      let isImDealCountChange = false
      if (imDealCount < min || imDealCount > max) {
        imDealCount = imDealCount < min ? min : imDealCount
        imDealCount = imDealCount > max ? max : imDealCount
        isImDealCountChange = true
      }
      commit(types.GET_CURRENT_USER, { currentUser: response.user })
      if (isImDealCountChange) {
        let data1 = {}
        Vue.set(data1, 'imDealCount', imDealCount)
        commit(types.UPDATE_CURRENT_USER, data1)
        dispatch('updateCurrentUser', { 'imDealCount': data1.imDealCount })
      }
    }).catch(err => {
      console.log(err)
      // 'message.default_tips'
    })
}
/**
 * 更新当前座席信息最大处理数
 */
export const updateCurrentUser = ({ commit }, data) => {
  let isAiRobot = true
  if (data.isAiRobot) {
    delete data.isAiRobot
  } else {
    isAiRobot = false
  }
  return config.updateCurrentUser(data)
    .then(response => {
      if (response.success) {
        // flag通常情况下不传，值为false   当设置更改了之后，导致当前会话上限更改的时候才会传输
        if (!isAiRobot) {
          let data1 = {}
          Vue.set(data1, 'imDealCount', data.imDealCount)
          commit(types.UPDATE_CURRENT_USER, data1)
        }
        return response
      } else {
        commit(types.SET_ERROR, 'message.default_tips')
      }
    }).catch(err => {
      console.log(err)
      // 'message.default_tips'
    })
}
/**
 * 定位客户
 * @param {String} data.customerId 客户id
 * @param {String} data.callId
 * @param {String} data.custName 客户名称
 */
export const locationCustomer = ({ commit }, data) => {
  let customer = data.customer
  let submenu = data.submenu
  let sessionId = data.sessionId
  console.log(data)
  delete data.submenu
  delete data.sessionId
  delete data.customer
  return webchat.locationCustomer(data)
    .then(
      response => {
        if (response.success) {
          commit(types.LOCATION_CUSTOMER, { customer, submenu, sessionId })
        }
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 解除客户绑定
 * @param {String} data.customerId 客户id
 */
export const deleteCustomerImRelation = ({ commit }, data) => {
  let sessionId = data.sessionId
  let sid = data.sid
  let sName = data.sName
  delete data.sName
  delete data.sessionId
  return webchat.deleteCustomerImRelation(data)
    .then(
      response => {
        if (response.success) {
          commit(types.DELETE_CUSTOMER_IM_RELATION, sessionId)
          commit(types.UPDATE_WEBCHAT_RELATION_CUSTOMER, { sid: sid, customer: { status: '', _id: '', name: sName } })
        }
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 座席接受到消息
 * @param {String} data._id 会话id
 */
export const dealMsg = ({ commit }, data) => {
  if (data.tabType === 'webchat_todo') {
    delete data.tabType
    return webchat.dealMsg(data)
      .then(
        response => {
          if (response.success) {
            commit(types.DEAL_MSG, { sessionId: data._id })
          }
        }
      ).catch(() => {
        // 'message.default_tips'
      })
  }
}
/**
 * 座席回复消息
 * @param {String} contentType 消息类型,
 * @param {String} platform 平台
 * @param {String} accessId 接入号ID，全局唯一
 * @param {String} agentFirstReplyTime 座席首次回复时间
 * @param {String} manualTime  人工接待时间戳
 * @param {String} status 消息状态
 * @param {String} lastRedirectTime 最后转接座席或技能组时间戳
 * @param {String} lastClaimTime 最后领取时间戳
 * @param {String} content 消息内容
 * @param {String} firstReply 是否是首次回复
 * @param {String} timeStamp 时间戳
 * @param {String} createTime 创建时间
 * @param {String} uploadTimestamp 发送图片/文件时才有的上传时间戳
 */
export const replyMsg = ({ commit, state, rootState, dispatch }, { data, index }) => {
  let contentNew = data.contentNew
  let contentHasUrl = data.contentHasUrl
  let aiContentText = data.aiContentText || ''
  let eventLogData = { // 超时日志上传参数
    timeStart: new Date().getTime(),
    apiType: 'replyMsg',
    type: 'requestTimeout',
    sid: data.sid,
    sessionId: data.sessionId
  }

  delete data.contentHasUrl
  delete data.contentNew
  delete data.aiContentText
  return webchat.replyMsg(data)
    .then(
      response => {
        if (response.success) {
          eventLogData.endTime = new Date().getTime()
          eventLogData.time = eventLogData.endTime - eventLogData.timeStart
          let account = rootState.session.account.account
          if (((eventLogData.endTime - eventLogData.timeStart) > 2000) && account === 'N00000000011') {
            dispatch('collectEventLog', eventLogData)
          }
          response.row.message = decodeURIComponent(response.row.content)
          response.row.message = renderEmoji(response.row.message)
          removeTimer({ commit, state }, data.sessionId)
          if (response.success) {
            Vue.set(response.row, 'sendStatus', 'success')
          } else {
            Vue.set(response.row, 'sendStatus', 'fail')
          }
          if (response.row.contentType === 'file') {
            Vue.set(response.row, 'fileName', transferFileContent(response.row.message))
            Vue.set(response.row, 'mp3Suffix', checkSuffix(response.row.fileName, 'mp3,wav,ogg'))
            if (response.row.mp3Suffix) {
              Vue.set(response.row, 'play', false)
            }
          }
          if (contentNew) {
            response.row.message = contentNew
            response.row.contentHasUrl = contentHasUrl
          }
          if (aiContentText) {
            response.row.aiContentText = aiContentText
          }
          if (response.blackIp) {
            Message({ message: m7Language('webchat.addIPBlackListNotify'), type: 'error' })
          }
          commit(types.M7AIROBOT_ANSWERS, { sessionId: data.sessionId, list: [] })
          commit(types.REPLY_MSG, { data: response.row, index: index })
          commit(types.SORTLISTBY_TYPE)
        } else {
          let errorMsg = ''
          if (response.errorCode) {
            if (data.platform === 'weixin' && response.errorCode === 45047) {
              errorMsg = 'webchat.errorCode.errcode_' + response.errorCode + '_weixin'
            } else {
              errorMsg = 'webchat.errorCode.errcode_' + response.errorCode
            }
            // Message({message: m7Language(errorMsg), type: 'error'}) // 解决连续弹出错误
            commit(gtypes.SET_ERROR, errorMsg)
          }
          // 发送消息为敏感词
          if (response.illegalWord) {
            state.current.webchat_todo.messageList[data.sessionId].splice(index, 1)
            Message({ message: m7Language('webchat.illegal'), type: 'error' })
          }
          if (response.message === 'webchat.oldLeaveMsg') {
            state.current.webchat_todo.messageList[data.sessionId].splice(index, 1)
          }
          if (response.message === "FIND_SESSIONFORM_ERROR") {
            Message({ message: m7Language('webchat.FIND_SESSIONFORM_ERROR'), type: 'error' })
            return ''
          }
        }
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 新增自定义快捷回复语
 * @param {String} data.content "test"
 * @param {String} data.quickContent "test"
 * @param {String} data.tagParentId ""
 * @param {String} data.moduleType "webchat"
 */
export const newAddAgentQuickReply = ({ commit }, data) => {
  return webchat.newAddAgentQuickReply(data)
    .then(
      response => {
        if (response.success) {
        }
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 公共快捷回复增加引用统计
 * @param {String} data._id "快捷回复id"
 */
export const addCommonQuickReplyNum = ({ commit }, data) => {
  return webchat.addCommonQuickReplyNum(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 个人快捷回复增加引用统计
 * @param {String} data._id "快捷回复id"
 */
export const addAgentQuickReplyNum = ({ commit }, data) => {
  return webchat.addAgentQuickReplyNum(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 更新自定义快捷回复语
 * @param {String} data._id ""
 * @param {String} data.moduleType "webchat"
 * @param {String} data.content ""
 * @param {String} data.quickContent ""
 */
export const newUpdateAgentQuickReply = ({ commit }, data) => {
  return webchat.newUpdateAgentQuickReply(data)
    .then(
      response => {
        if (response.success) {
        }
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 删除自定义快捷回复语
 * @param {Array} data._ids []
 * @param {String} data.moduleType "webchat"
 * @param {String} data.content ""
 * @param {String} data.quickContent ""
 */
export const newDeleteAgentQuickReply = ({ commit }, data) => {
  return webchat.newDeleteAgentQuickReply(data)
    .then(
      response => {
        if (response.success) {
        }
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}

/**
 * 获取在线咨询自定义快捷回复的分类标签
 * @param {String} data.moduleType "webchat"/"email"
 */
export const newQueryAgentQuickReplyTag = ({ commit }, data) => {
  return webchat.newQueryAgentQuickReplyTag(data)
    .then(
      response => {
        if (response.success) {
        }
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 添加在线咨询自定义快捷回复的分类标签
 * @param {String} data.name "test"
 * @param {String} data.moduleType "webchat"
 * @param {Number} data.sort 0
 */
export const newAddAgentQuickReplyTag = ({ commit }, data) => {
  return webchat.newAddAgentQuickReplyTag(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 更新自定义快捷回复的分类标签
 * @param {String} data._id "test"
 * @param {String} data.moduleType "webchat"
 * @param {String} data.name "test2"
 * @param {Number} data.sort 0
 */
export const newUpdateAgentQuickReplyTag = ({ commit }, data) => {
  return webchat.newUpdateAgentQuickReplyTag(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 删除在线咨询自定义快捷回复的分类标签信息
 * @param {Array} data.ids []
 * @param {String} data.moduleType "webchat"
 */
export const newDeleteAgentQuickReplyTag = ({ commit }, data) => {
  return webchat.newDeleteAgentQuickReplyTag(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 在线咨询自定义快捷回复变更分类
 * @param {String} data.moduleType "webchat"/"email"
 */
export const changeCategoryOfQuickReplies = ({ commit }, data) => {
  return webchat.changeCategoryOfQuickReplies(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 搜索自定义快捷回复
 * @param {String} data.moduleType "webchat"/"email"
 */
export const newQueryAgentQuickReply = ({ commit }, data) => {
  return webchat.newQueryAgentQuickReply(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 搜索全部自定义快捷回复
 * @param {String} data.moduleType "webchat"/"email"
 */
export const queryAllAgentQuickReplyNew = ({ commit }, data) => {
  return webchat.queryAllAgentQuickReplyNew(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 快捷回复输入联系时,查询全部回复语(自定义+系统)
 * @param {String} data.moduleType "webchat"/"email"
 */
export const getAllQuickReplyListNew = ({ commit }, data) => {
  return webchat.getAllQuickReplyListNew(data)
    .then(
      response => {
        if (response.success) {
          commit(types.GET_ALL_QUICK_REPLY_LIST, response.list)
        }
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 在线咨询右侧快捷回复模糊搜索
 * @param {String} data.moduleType "webchat"/"email"
 */
export const newSearchQuickReply = ({ commit }, data) => {
  // let index = data.index
  return webchat.newSearchQuickReply(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 会话转接给指定座席或技能组
 * @param {String} data._id
 * @param {String} data.toUser 转接到座席id
 * @param {String} data.toUserName 座席名称
 * @param {String} data.sid 访客id
 * @param {String} data.queueId 转入技能组id
 * @param {String} data.toPeer 转入技能组id
 * @param {Boolean} data.noClose 转接后是否关闭会话
 */
export const redirectWebchatSession = ({ commit, state }, data) => {
  if (data.onlyUpdate) {
    removeTimer({ commit, state }, data._id)
    commit(types.REMOVE_SESSION, data._id)
    commit(types.SORTLISTBY_TYPE)
    return
  }
  let result = state.webchatList.webchat_todo.list.filter((item) => item._id === data._id)
  if (result && result.length > 0) {
    data.message = result[0].lastMessage
    data.contentType = result[0].contentType
    data.showHtml = result[0].showHtml || ''
  }
  return new Promise(function (resolve) {
    webchat.redirectWebchatSession(data)
      .then(
        response => {
          if (response.success && !data.noClose) {
            removeTimer({ commit, state }, data._id)
            commit(types.REMOVE_SESSION, data._id)
            commit(types.SORTLISTBY_TYPE)
          }
          resolve(response.success)
        }
      ).catch(() => {
        // 'message.default_tips'
      })
  })
}
export const redirectSessionCancel = ({ commit, state }, data) => {
  return webchat.redirectSessionCancel(data)
}
/**
 * 会话批量转接给指定座席或技能组
 * @param {String} data.toUser 转接到座席id
 * @param {String} data.toUserName 座席名称
 * @param {String} data.queueId 转入技能组id
 * @param {String} data.toPeer 转入技能组id
 */
export const batchRedirectWebchatSession = ({ commit, state, rootState, dispatch }, data) => {
  return webchat.batchRedirectWebchatSession(data).then(response => {
    if (response.success) {
      if (response.list && response.list.length > 0) {
        response.list.forEach(item => {
          removeTimer({ commit, state }, item)
          commit(types.REMOVE_SESSION, item)
          commit(types.SORTLISTBY_TYPE)
          dispatch('changeInvite', { todo: 'delete', sessionId: item })
        })
      }
      return response
    }
  })
    .catch(() => {
    })
}
/**
 * 推送排队信息至客户端:
 * @param {String}
 */
export const pushQueueNumToWebChatClients = ({ commit }, data) => {
  return webchat.pushQueueNumToWebChatClients(data)
    .then(
      response => {
        if (response.success) {
        }
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 邀请座席协助
 * @param {String} data._id
 * @param {String} data.invitedUser 被邀请座席id
 * @param {String} data.invitedUserName 被邀请座席名称
 * @param {String} data.sid
 */
export const inviteGroupSession = ({ commit }, data) => {
  return new Promise(function (resolve) {
    webchat.inviteGroupSession(data)
      .then(
        response => {
          if (response.success) {
            commit(types.CHANGE_INVITE_NOTIFY, {
              userName: data.invitedUserName,
              sessionId: data._id,
              sid: data.sid,
              toPeer: ''
            })
            let conData = {
              userName: data.invitedUserName,
              sessionId: data._id,
              sid: data.sid
            }
            commit(types.UPDATE_WEBCHAT_INVITECONDATA, { data: conData, value: true })
          }
          resolve(response.success)
        }
      ).catch(() => {
        // 'message.default_tips'
      })
  })
}
/**
 * 接受会话邀请
 * @param {String} data._id
 * @param {String} data.sid 会话sid,可以为空字符串
 * @param {String} data.toPeer 技能组编号
 * invitedUserName
 */
export const acceptGroupSession = ({ commit, state }, data) => {
  return webchat.acceptGroupSession(data)
    .then(
      response => {
        if (response.success) {
          response.session.inviteUserStatus = 'accept'
          let isEsc = false
          let data = response.session
          if (data.contentType === 'text') {
            if (data.showHtml === true || data.showHtml === 'true') {
              isEsc = true
            }
          }
          data.message = data.message === 'undefined' ? '' : data.message
          data.message = renderEmoji(data.message, isEsc)
          if (data.contentType === 'text') {
            data.contentHasUrl = ''
            let oldContent = data.message
            let contentNew = msgConvertion(data.message)
            data.message = contentNew
            if (oldContent !== contentNew) {
              data.contentHasUrl = 'have'
            }
          }
          if (data.contentType === 'file') {
            data.fileName = transferFileContent(data.message)
            Vue.set(data, 'mp3Suffix', checkSuffix(data.fileName, 'mp3,wav,ogg'))
            if (data.mp3Suffix) {
              Vue.set(data, 'play', false)
            }
          } else if (data.contentType === 'voice') {
            Vue.set(data, 'play', false)
          }
          commit(types.UPDATE_WEBCHAT_MESSAGE_LIST, data)
          webchatHourMeter({ commit, state }, {
            startWaitTimer: data.startWaitTimer,
            online: data.userStatus,
            sessionId: data._id
          })
          commit(types.SORTLISTBY_TYPE)
        }
        return response
      }
    )
    .catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 拒绝会话邀请
 * @param {String} data._id 会话id
 */
export const refusedGroupSession = ({ commit }, data) => {
  return webchat.refusedGroupSession(data)
    .then(
      response => {
        if (response.success) {
        }
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 退出会话邀请
 */
export const quitGroupSession = ({ commit, state }, data) => {
  return webchat.quitGroupSession(data)
    .then(response => {
      if (response && response.success) {
        removeTimer({ commit, state }, data._id)
        commit(types.REMOVE_SESSION, data._id)
        commit(types.SORTLISTBY_TYPE)
        return response
      }
    }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 踢出邀请的座席
 * @param {String} data._id 会话id
 */
export const kickGroupSession = ({ commit }, data) => {
  return webchat.kickGroupSession(data)
    .then(
      response => {
        if (response.success) {
          commit(types.SHOW_INVITE_BTN, { flag: true, sessionId: data._id })
          commit(types.UPDATE_INVITE_INFO, {
            _id: data._id,
            inviteUserStatus: '',
            invitedUserName: '',
            assistAgent: false
          })
        }
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
// 抢接会话
export const grabWebchatSession = ({ commit }, data) => {
  return new Promise(function (resolve) {
    webchat.grabWebchatSession(data)
      .then(
        response => {
          if (response.success) {
            commit(gtypes.SET_SUCCESS, 'webchat.grabSuccess')
            resolve()
          }
        }
      ).catch(() => {
        // 'message.default_tips'
      })
  })
}
/**
 * 推送满意度评价
 * @param {String} id 会话id
 * @param {String} sid 访客id,
 * @param {String} platform 平台
 * @param {String} createTime 创建时间
 */
export const pushImCSRInfo = ({ commit, state }, data) => {
  return webchat.pushImCSRInfo(data)
    .then(
      response => {
        if (response.success) {
          let obj = {
            type: 'system',
            platform: data.platform,
            sid: data.sid,
            createTime: response.time,
            message: m7Language('webchat.sendEvaluation'),
            _id: data.sessionId
          }
          // 重置访客等待时间
          removeTimer({ commit, state }, data._id)
          // 更新消息列表
          commit(types.UPDATE_WEBCHAT_MESSAGE_LIST, obj)
          commit(types.SORTLISTBY_TYPE)
        } else {
          let errorMsg = ''
          if (response.errorCode) {
            if (data.platform === 'weixin' && response.errorCode === 45047) {
              errorMsg = 'webchat.errorCode.errcode_' + response.errorCode + '_weixin'
            } else {
              errorMsg = 'webchat.errorCode.errcode_' + response.errorCode
            }
            // Message({message: m7Language(errorMsg), type: 'error'}) // 解决连续弹出错误
            commit(gtypes.SET_ERROR, errorMsg)
          }
        }
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 结束会话
 * @param {String} data._id 会话id
 * @param {String} data.sid 访客id
 * @param {String} data.finishReason 结束类型
 * @param {String} data.finishKey 结束会话类型id
 * @param {String} data.remark 备注
 */
export const finishWebchatSession = ({ commit, state, dispatch }, data) => {
  let finishiArr = data.finishiArr || []
  return new Promise(function (resolve) {
    webchat.finishWebchatSession(data)
      .then(
        response => {
          if (response.success) {
            if (!finishiArr.length) {
              finishiArr.push({ _id: data._id })
            }
            finishiArr.forEach((item) => {
              removeTimer({ commit, state }, item._id)
              commit(types.REMOVE_SESSION, item._id)
              commit(types.SORTLISTBY_TYPE)
              // 结束会话的时候删除掉邀请信息
              dispatch('changeInvite', { todo: 'delete', sessionId: item._id })
            })
            resolve(response.success)
          }
        }
      ).catch(() => {
        // 'message.default_tips'
      })
  })
}

/**
 * 在线咨询全部中结束会话
 * @param {String} data._id 会话id
 * @param {String} data.sid 访客id
 * @param {String} data.finishReason 结束类型
 * @param {String} data.finishKey 结束会话类型id
 * @param {String} data.remark 备注
 */
export const finishUndealWebchatSession = ({ commit, state, dispatch }, data) => {
  return webchat.finishUndealWebchatSession(data).then(
    response => {
      if (response.success) {
        return response
      }
    }
  ).catch(() => {
    // 'message.default_tips'
  })
}

/**
 * 取消会话邀请
 * @param {String} data._id 会话id
 */
export const cancelGroupSession = ({ commit }, data) => {
  return webchat.cancelGroupSession(data)
    .then(
      response => {
        if (response.success) {
        }
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 提醒访客座席正在输入中
 * @param {String} data.sid 会话id
 * @param {String} data.timestamp 时间戳
 */
export const typeNotice = ({ commit }, data) => {
  return webchat.typeNotice(data)
    .then(
      response => {
        if (response.success) {
        }
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 更新会话的备注信息
 * @param {String} data.accessId 接入号
 * @param {String} data.sid 访客id
 * @param {String} data.content 备注内容
 */
export const updateWebchatSessionRemark = ({ commit }, remark) => {
  return webchat.updateWebchatSessionRemark(remark)
    .then(
      response => {
        if (response.success) {
          commit(gtypes.SET_SUCCESS, 'webchat.remarkSuccess')
          commit(types.UPDATE_WEBCHAT_SESSION_REMARK, remark)
        }
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}

export const redirectSessionCallback = ({ commit }, remark) => {
  return webchat.redirectSessionCallback(remark)
}

export const loadUsers2Chat = ({ dispatch }, data) => {
  return new Promise(function (resolve) {
    let isEnable = data.isEnable
    let hideMe = data.hideMe
    let currentId = data.currentId
    let isEmpty = data.isEmpty
    dispatch('getCache', { type: 'agents' }).then((agents) => {
      let agents1 = []
      if (isEnable) {
        for (let i = 0; i < agents.length; i++) {
          if (agents[i].status === 'enable') {
            agents1.push(agents[i])
          }
        }
      } else {
        for (let k = 0; k < agents.length; k++) {
          agents1.push(agents[k])
        }
      }
      if (hideMe) {
        for (let j = 0; j < agents1.length; j++) {
          if (agents1[j]._id === currentId) {
            agents1.splice(j, 1)
            break
          }
        }
      }
      let agents2 = []
      if (isEmpty) {
        let emptyAgents = [{ _id: '', displayName: '放入领取池', pinyin: 'wusuoshuren', exten: '', status: 'enable' }]
        agents2 = emptyAgents.concat(agents1)
      } else {
        agents2 = agents1
      }
      resolve(agents2)
    })
  })
}

export const getOnlineAgent = ({ commit, rootState, dispatch }, { data, type }) => {
  // 获取所有技能组相关数据
  return webchat
    .showAllSkillGroup(data)
    .then((response) => {
      // onlineChannelAgent在线坐席
      let p1 = dispatch('getCache', { type: 'onlineChannelAgent', loadFromServer: true })
      // 这个是添加 空项 可点 隐藏坐席自己
      let p3 = dispatch('loadUsers2Chat', {
        isEnable: true,
        isEmpty: true,
        currentId: rootState.session.user._id,
        hideMe: true
      })
      let p = Promise.all([p1, p3])
      return p.then(async ([onlines, agents]) => {
        // 需要根据onlines返回的内容，再次查询在线的座席当前待处理会话数量
        var onlineArray = []
        onlines.map((item) => {
          onlineArray.push(item._id)
        })
        var formData = { onlineAgentLists: onlineArray }
        const limitRes = await webchat.getOnlineAgentIMDealLimit(formData)
        return webchat.getOnlineAgentIMDealCount(formData).then((resCount) => {
          response.data = response.data
            .map((item) => {
              let accessAgents = item.AssignMembers || []
              let resultAgents = []
              let resultAgents2 = []
              // 根据loadUsers2Chat组装技能组内坐席
              for (let i = 0; i < accessAgents.length; i++) {
                let agent = accessAgents[i]
                for (let j = 0; j < agents.length; j++) {
                  let _agent = agents[j]
                  if (_agent._id === agent.agentID) {
                    resultAgents.push(_agent)
                    break
                  }
                }
              }
              // 过滤掉不在线坐席
              for (let i = 0; i < onlines.length; i++) {
                let agent = onlines[i]
                for (let j = 0; j < resultAgents.length; j++) {
                  let _agent = resultAgents[j]
                  if (_agent._id === agent._id) {
                    _agent.online = true
                    resultAgents2.push(_agent)
                    break
                  }
                }
              }
              // 给每个在线座席设置上会话待处理数
              if (resultAgents2.length) {
                resultAgents2.map((itemAgent) => {
                  itemAgent.chatNum = resCount.onlineAgentIMDealCountObj[itemAgent._id] || '' // 当前接待量
                  itemAgent.maxChatNum = limitRes.onlineAgentIMDealLimitObj[itemAgent._id] || '' // 会话上限
                })
              }
              item.open = false
              item.AssignMembers = resultAgents2
              item.chatNum = resultAgents2.map((i) => i.chatNum).reduce((pre, cur) => +pre + +cur, 0)
              item.maxChatNum = resultAgents2.map((i) => i.maxChatNum).reduce((pre, cur) => +pre + +cur, 0)
              return item
            }).filter(item => item.AssignMembers.length > 0)
            return response.data
          })
        })
      }).catch(() => {
      // 'message.default_tips'
    })
}

export const getPeerOnlineAgent = ({ commit, rootState, dispatch }, peerId) => {
  return new Promise(function (resolve) {
    let newGroups = []
    let p2 = dispatch('getCache', { type: 'onlineChannelAgent', loadFromServer: true })
    let p3 = dispatch('getCache', { type: 'accessChannelAgent' })
    let p4 = dispatch('getCache', { type: 'channelGlobalSet' })
    let p = Promise.all([p2, p3, p4])
    p.then(([onlines, peer, globalSet]) => {
      // 需要根据onlines返回的内容，再次查询在线的座席当前待处理会话数量
      var onlineArray = []
      onlines.map((item) => {
        onlineArray.push(item._id)
      })
      var formData = { "onlineAgentLists": onlineArray }
      return webchat.getOnlineAgentIMDealCount(formData).then(resCount => {
        let accessAgents = []
        if (peer) {
          peer.forEach((item) => {
            if (globalSet.inviteGroupSessionAll && globalSet.inviteGroupSessionAll === 'true') {
              accessAgents = accessAgents.concat(item.agents)
            } else {
              if (item._id === peerId) {
                accessAgents = item.agents
              }
            }
          })
        }
        let resultAgents = []
        var agentMap = new Map()
        for (let i = 0; i < accessAgents.length; i++) {
          let agent = accessAgents[i]
          for (let j = 0; j < onlines.length; j++) {
            let _agent = onlines[j]
            if (_agent._id === agent.agentID && _agent._id !== rootState.session.user._id) {
              _agent.online = true
              if (!agentMap.get(_agent._id)) {
                agentMap.set(_agent._id, true)
                resultAgents.push(_agent.user)
              }
              break
            }
          }
        }
        if (resultAgents.length) {
          resultAgents.map((itemAgent) => {
            itemAgent.chatNum = resCount.onlineAgentIMDealCountObj[itemAgent._id] || ''
          })
          newGroups.push({ AssignMembers: resultAgents })
        }
        resolve(newGroups)
      })
    })
  })
}

let syncOnlineAgent = function ({ dispatch, commit }, data) {
  dispatch('getCache', { type: 'onlineChannelAgent' }).then((onlines) => {
    let uid = data.userId
    let online = data.online
    let has = false
    for (let i = 0; i < onlines.length; i++) {
      let agent = onlines[i]
      if (agent._id === uid) {
        has = true
        break
      }
    }
    if (online) {
      if (!has) {
        dispatch('addCache', { type: 'onlineChannelAgent', data: { _id: uid } })
        // 更新坐席状态
        commit(monitotTypes.UPDATE_CLAIM_STATUS, { user: uid, status: true })
        // 更新技能组状态
        commit(monitotTypes.MULTI_SKILL_AGENT_CHECK, { data: data, operate: 'add' })
      }
    } else {
      if (has) {
        dispatch('removeCache', { type: 'onlineChannelAgent', id: uid })
        commit(monitotTypes.UPDATE_CLAIM_STATUS, { user: uid, status: false })
        commit(monitotTypes.MULTI_SKILL_AGENT_CHECK, { data: data, operate: 'remove' })
      }
    }
  })
}

let transferFileContent = function (params) {
  let paramsNew = params.split('?fileName=')
  let html = ''
  if (paramsNew.length > 1) {
    let params2 = paramsNew[1].split('?fileSize=')
    if (params2.length) {
      html = params2[0]
    }
  }
  return html
}
let transferWxkfFileContent = function (params) {
  let paramsNew = params.split('/')
  let html = ''
  if (paramsNew.length > 1) {
    let paramsNewTest = paramsNew[paramsNew.length - 1].split('?fileName=')
    if (paramsNewTest.length > 1) {
      html = paramsNewTest[0]
      return html
    }
    let params2 = paramsNew[paramsNew.length - 1].split('.')
    if (params2.length) {
      html = paramsNew[paramsNew.length - 1]
    }
  }
  return html
}

export const dispatchWebchat = ({ commit, state, rootState, dispatch }, evtJson) => {
  let data = evtJson.Data
  let event = evtJson.Event
  let isMe = evtJson.Foryou
  let obj = {}
  for (let i in data) {
    let value = data[i]
    let key = i.replace(/^\S/, function (s) {
      return s.toLowerCase()
    })
    obj[key] = value
  }
  try {
    if (obj.sName) {
      obj.sName = decodeURIComponent(decodeURIComponent(obj.sName))
    }
  } catch (e) {
    if (obj.sName) {
      obj.sName = decodeURIComponent(obj.sName)
    }
  }
  if (obj.content) {
    try {
      obj.content = decodeURIComponent(obj.content)
    } catch (e) {
      obj.content = obj.content.replace(/%26/g, '&')
      obj.content = obj.content.replace(/%23/g, '#')
      obj.content = obj.content.replace(/%3A/g, ':')
      obj.content = obj.content.replace(/%24/g, '$')
      obj.content = obj.content.replace(/%40/g, '@')
      obj.content = obj.content.replace(/%2B/g, '+')
      obj.content = obj.content.replace(/%3D/g, '=')
      obj.content = obj.content.replace(/%2F/g, '/')
    }
  }
  if (obj.cardInfo) {
    let cardInfo = decodeURIComponent(obj.cardInfo)
    obj.cardInfo = JSON.parse(cardInfo)
  }
  if (event === 'sendMsgResult' && isMe) { // 微信小程序&&抖音发送错误事件
    if (!data.success) {
      commit(types.REPLY_MSG_ERROR, { sessionId: data.sessionId, messageId: data.messageId, errCode: data.errcode })
      let errorMsg = ''
      if (data.platform && data.platform === 'dy') {
        errorMsg = 'webchat.dyErrorCode.dyerrcode_' + data.errcode
      } else if (data.platform && data.platform === 'wxkf') {
        errorMsg = 'webchat.wxkfErrorCode.wxkferrcode_' + data.errcode
      } else {
        errorMsg = 'webchat.errorCode.errcode_' + data.errcode
      }
      if (state.currentUser._id === data.user) { // 三方会话不弹消息错误弹窗
        Message({ message: m7Language(errorMsg), type: 'error' }) // 解决连续弹出错误
      }
      return
    }
  }
  if (event === 'NewWebchat') { // evnet 为 'NewWebchat'的事件
    if (obj.contentType === 'screenShare' && obj.screenShareStatus === 'custRefuse') {
      // 屏幕分享对方拒绝
      let msg = {
        status: false,
        id: '',
        name: ''
      }
      commit(types.SET_SHARESCREEN, msg)
    } else if (obj.type === 'invitedVideo') {
      return
    }
  }
  if (event === 'NewNotify') { // evnet 为 'NewNotify'的事件
    if ((obj.type === 'robotAssist' || obj.type === 'm7AIBotAssist') && obj.assistListStr) { // 辅助机器人
      let list = []
      try {
        list = JSON.parse(decodeURIComponent(obj.assistListStr))
      } catch (e) {
        console.log(e)
      }
      let data = {
        sessionId: obj.sessionId,
        list: list
      }
      commit(types.M7AIROBOT_ANSWERS, data)
      return
    } else if (obj.type === 'acceptVideo') {
      return
    } else if (obj.type === 'hungupVideo') {
      let data = Math.random()
      commit(types.VIDEOHANGUP, data)
      let inviteMsg = {
        roomId: '',
        videoInviteSessionid: '',
        platform: ''
      }
      commit(types.UPDATE_VIDEO_INVITE_DATA, inviteMsg)
      return
    } else if (obj.type === 'refuseVideo' || obj.type === 'cancelVideo') {
      commit(types.UPDATE_VIDEO_INVITE_STATUS, false)
      commit(types.UPDATE_VIDEO_CHAT_STATUS, false)
      let inviteMsg = {
        roomId: '',
        videoInviteSessionid: '',
        platform: ''
      }
      commit(types.UPDATE_VIDEO_INVITE_DATA, inviteMsg)
      return
    } else if (obj.type === 'acceptScreenShare') {
      return
    } else if (obj.type === 'agentPushStatus') {
      syncOnlineAgent({ dispatch, commit }, obj)
    } else if (obj.type === 'chatSessionClose' && isMe) {
      removeTodoItem({ commit, state }, obj._id)
    } else if (obj.type === 'invitedVideo') {
      // 接收到视频聊天邀请
      commit(types.UPDATE_VIDEO_INVITE_PERSONNEL, "customer")
      commit(types.UPDATE_VIDEO_INVITE_STATUS, true)
      let inviteMsg = {
        videoInviteSessionid: obj._id,
        videoType: obj.videoType,
        platform: obj.platform || '',
        roomId: obj.roomId || '',
        password: obj.password || ''
      }
      commit(types.UPDATE_VIDEO_INVITE_DATA, inviteMsg)
    } else if (obj.type === 'withdrawMessage') {
      //  三方会话状态下，另一坐席撤回消息
      let user = getCache('agents', obj.from)
      let displayName = ''
      if (user) {
        displayName = user.displayName
      }
      let message = m7Language('webchat.ShieldMsg')
      if (obj.invitedUser) {
        message = m7Language('webchat.ShieldMsgAgent', { agent: displayName })
      }
      commit(types.SHIELD_MSG, {
        data: obj,
        message: message,
        flag: true
      })
    } else if (obj.type === 'removeVideo') {
      // 接收到移除视频聊天邀请
      commit(types.UPDATE_VIDEO_INVITE_STATUS, false)
      let inviteMsg = {
        videoInviteSessionid: '',
        videoInviteToken: '',
        roomId: '',
        videoType: '',
        password: ''
      }
      commit(types.UPDATE_VIDEO_INVITE_DATA, inviteMsg)
      // app 和 pc 同时在线 app 离线 pc会 推送 type === 'removeSession'
    } else if (obj.type === 'removeSession') {
      if (obj.sessionIds.length) {
        obj.sessionIds.forEach((item) => {
          commit(types.REMOVE_SESSION, item)
        })
      }
      // 关联客户被删除
    } else if (obj.type === 'delete_relation') {
      let sid = state.current.webchat_todo.currentSession[obj._id].sid
      let customerId = state.current.webchat_todo.currentCustomer._id
      dispatch('deleteCustomerImRelation', { customerId: customerId, sessionId: obj._id, sid: sid, sName: obj.sName })
    } else if (obj.type === 'changePeer') {
      let mailQueues = getCache('mailQueues')
      let queueDisplayName = ';'
      for (let i = 0; i < mailQueues.length; i++) {
        if (mailQueues[i].Exten === obj.toPeer) {
          queueDisplayName = mailQueues[i].DisplayName
        }
      }
      obj.status = 'changePeer'
      obj.content = '用户流转进了【' + queueDisplayName + '】技能组'
      if (state.webchatList.webchat_todo.init) {
        webchatTodoItemAdd({ commit, state }, obj)
      } else {
        let data = { submenu: 'webchat_todo' }
        dispatch('queryWebchatList', data)
      }
    } else if (obj.type === 'invited_changePeer') { // 访客端转技能组 如果会话邀请过其他座席，向邀请座席推送通知
      if (data.invitedUser === rootState.session.user._id) {
        removeTodoItem({ commit, state }, obj._id)
      }
      // 新消息通知
    } else if (obj.type === 'refreshUndealNum') {
      if (evtJson.timestamp > state.undealNumTimeStamp) {
        Vue.set(obj, 'timestamp', evtJson.timestamp)
        commit(types.SET_WEBCHAT_UNDEALNUM, obj)
      }
    } else if (obj.type === 'refreshImDealCount') {
      // 手机端更改座席上限,pc端跟着变化
      commit(types.REFRESH_IM_DEAL_COUNT, obj.imDealCount)
    } else if (obj.type === 'webchat') { // type 为 'webchat' 类型的事件
      // 自动结束会话
      if (obj.operation === 'autoClose' && isMe) {
        if (state.isVideoing && obj._id === state.videoChatData.videoSessionid) {
          var originator = this.$store.state.webchat.invitePersonnel || 'agent'
          let msg = {
            _id: state.videoChatData.videoSessionid,
            operation: 'cancel',
            originator: originator
          }
          dispatch('cancelVideoInvite', msg)
        }
        removeTodoItem({ commit, state }, obj._id)
        let content = m7Language('notify.webchat6')
        commit(gtypes.SET_SUCCESS, obj.sName + content)
        commit(gtypes.SET_NOTIFY, { tag: 'webchat', notify: obj })
        // 切换技能组
      } else if (obj.operation === 'changePeer') {
        removeTodoItem({ commit, state }, obj._id)
        // 访客端更换客服
      } else if (obj.operation === 'redirectAgent') {
        removeTodoItem({ commit, state }, obj._id)
        // 主动领取会话
      } else if (obj.operation === 'grab_redirect') {
        removeTodoItem({ commit, state }, obj._id)
        let content1 = m7Language('notify.webchat7')
        let content2 = m7Language('notify.webchat8')
        commit(gtypes.SET_SUCCESS, obj.toUserName + content1 + obj.sName + content2)
        commit(gtypes.SET_NOTIFY, { tag: 'webchat', notify: obj })
        // 邀请坐席会话聊天
      } else if (obj.operation === 'invited') {
        commit(types.CHANGE_INVITE_NOTIFY, { userName: obj.username, sessionId: obj._id, sid: obj.sid, toPeer: obj.toPeer })
        dispatch('changeInvite', { userName: obj.username, sessionId: obj._id, sid: obj.sid, toPeer: obj.toPeer, todo: 'add', type: 'beInvited' })
        commit(gtypes.SET_NOTIFY, { tag: 'webchat', notify: obj })
        // 取消邀请坐席会话聊天
      } else if (obj.operation === 'invited_redirect') {
        // 会话被转接了
        removeTodoItem({ commit, state }, obj._id)
        dispatch('queryWebchatList', { 'submenu': 'webchat_todo' })
      } else if (obj.operation === 'invited_cancel') {
        dispatch('changeInvite', { todo: 'delete', sessionId: obj._id })
        // 邀请坐席会话聊天被踢出
      } else if (obj.operation === 'invite_kick') {
        commit(gtypes.SET_SUCCESS, 'notify.webchat15')
        removeTodoItem({ commit, state }, obj._id)
        commit(types.INVITE_KICK, obj._id)
        // 邀请坐席会话聊天会话被关闭
      } else if (obj.operation === 'invite_close') {
        commit(gtypes.SET_SUCCESS, 'notify.webchat16')
        removeTodoItem({ commit, state }, obj._id)
        dispatch('changeInvite', { todo: 'delete', sessionId: obj._id })
      } else if (obj.operation === 'invite_quit') {
        commit(types.SHOW_INVITE_BTN, { flag: !false, sessionId: obj._id })
        webchatTodoItemAdd({ commit, state }, obj)
      } else if (obj.operation === 'invite_handle') {
        let flag
        let notifyTitle = ''
        let invitedUserName = ''
        let inviteUserStatus = ''
        if (obj.accept === true) { // 邀请坐席会话聊天会话 对方同意了邀请
          notifyTitle = 'notify.webchat17'
          invitedUserName = getCache('agents', obj.from).displayName
          inviteUserStatus = 'accept'
          flag = true
        } else if (obj.accept === false) { // 邀请坐席会话聊天会话 对方拒绝了邀请
          notifyTitle = 'notify.webchat18'
          invitedUserName = ''
          inviteUserStatus = 'undeal'
          flag = false
        }
        console.log(invitedUserName)
        commit(types.SHOW_INVITE_BTN, { flag: !flag, sessionId: obj._id })
        commit(types.UPDATE_INVITE_INFO, { _id: obj._id, inviteUserStatus: inviteUserStatus, invitedUserName, assistAgent: flag })
        commit(types.CANCEL_WEBCHAT_INVITECONDATA, { sessionId: obj._id, value: false })
        commit(gtypes.SET_SUCCESS, notifyTitle)
        // 技能组流转
      } else if (obj.operation === 'redirect' && isMe) {
        commit(gtypes.SET_NOTIFY, { tag: 'webchat', notify: obj })
        Vue.set(obj, 'leakNum', obj.leakNum || 1)
        if (state.webchatList.webchat_todo.init) {
          webchatTodoItemAdd({ commit, state }, obj)
        } else {
          let data = { submenu: 'webchat_todo' }
          dispatch('queryWebchatList', data)
        }
      } else if (obj.operation === 'dealMsg') {
        commit(types.UPDATEDEALMSGSTATUS, { sessionId: data.sessionId })
      }
    }
  } else if (event === 'GroupMsg') {
    obj.msgType = 'groupMsg'
    if (obj.type === 'out') {
      removeTimer({ commit, state }, obj.sessionId)
    }
    if (state.webchatList.webchat_todo.init) {
      webchatTodoItemAdd({ commit, state }, obj)
    } else {
      let data = { submenu: 'webchat_todo' }
      dispatch('queryWebchatList', data)
    }
  } else if (event === 'VoiceToText') {
    if (data.ttsCode) {
      if (data.ttsCode === 21050003) {
        data.voiceMsg = m7Language('webchat.notFindVoiceMsg')
      } else if (data.ttsCode === 500) {
        data.voiceMsg = m7Language('webchat.voiceToMsgError')
        data.isFinish = false
      } else if (data.ttsCode === 400) {
        data.voiceMsg = '转写超时，请点击重新转写'
        data.isFinish = false
      } else {
        data.isFinish = true
      }
    }
    commit(types.VOICETOTEXT, { _id: data.chatSessionId, voiceMsg: data.voiceMsg, when: data.when, tabType: data.tabType })
  } else {
    // 消息预加载
    if (event === 'NewWebchat' && obj.msgType === 'typeNotice') {
      if (obj.ubaSessionId) {
        dispatch('changeStatus', obj)
      }
      commit(types.UPDATE_PRELOADED_MSG, { message: obj.content, flag: true, _id: obj._id })
    } else {
      if (isMe) {
        if (obj.msgType === 'newMsg' && obj.content) {
          if (obj.content === m7Language('notify.webchat11')) {
            let collectData = {
              type: 'collectNewMsg',
              sid: obj.sid,
              _id: obj._id,
              createTime: obj.createTime,
              toPeer: obj.toPeer
            }
            dispatch('collectEventLog', collectData)
          }
          if (obj.contentType !== 'video') {
            commit(gtypes.SET_NOTIFY, { tag: 'webchat', notify: obj })
          }
          if (event === 'NewWebchat' && obj.msgType === 'newMsg' && obj.ubaSessionId) {
            dispatch('changeStatus', obj)
          }
          if (obj.contentType === 'text' && !obj.showHtml) {
            // 获取消息中的线索
            var regs = [
              /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/g,
              /[1-9][0-9]{4,}/g,
              /0\d{2,3}-?\d{7,8}/g,
              /(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|16[6|7]|18[0|1|2|3|5|6|7|8|9])\d{8}/g];
            //  邮箱,QQ,座机,手机  四种正则
            var str = obj.content
            var myArray;
            var cues = [];
            // cues = regs.exec(str)
            for (let reg of regs) {
              while ((myArray = reg.exec(str)) !== null) {
                cues.push(myArray[0]);
              }
            }
            // dispatch('updateSessionCue', obj)
            if (cues.length) {
              var createTime = ''
              var arr = cues
              var currentCue = ''
              state.webchatList.webchat_todo.list.forEach((item, index) => {
                if (data._id === item._id) {
                  currentCue = item.cue || ''
                  arr.forEach((item, index) => {
                    if (currentCue.indexOf(item) === -1) {
                      if (currentCue) {
                        currentCue += ',' + item
                      } else {
                        currentCue += item
                      }
                    }
                  })
                  createTime = item.createTime
                  commit(types.UPDATE_SESSION_CUE, { data: currentCue, index: index, type: 'webchatList', todoType: 'webchat_todo' })
                }
              })
              if (state.current.webchat_todo.currentSession[data._id]) {
                currentCue = state.current.webchat_todo.currentSession[data._id].cue || ''
                arr.forEach((item, index) => {
                  if (currentCue.indexOf(item) === -1) {
                    if (currentCue) {
                      currentCue += ',' + item
                    } else {
                      currentCue += item
                    }
                  }
                })
                createTime = state.current.webchat_todo.currentSession[data._id].createTime
                commit(types.UPDATE_SESSION_CUE, { data: currentCue, _id: obj._id, type: 'current', todoType: 'webchat_todo' })
              }
              var sendData = {
                sessionId: obj._id,
                sid: obj.sid,
                cue: currentCue,
                createTime: createTime
              }
              dispatch('updateSessionCue', sendData)
            }
          }
        } else if (obj.msgType === 'disConn') { // 访客离线
          commit(types.SET_OFFORONLINE_STATUS, { _id: obj._id, statu: 'offline' })
          if (obj.disConnType === 'client namespace disconnect') {
            commit(gtypes.SET_NOTIFY, { tag: 'webchat', notify: obj })
          }
        } else if (obj.msgType === 'newConn') {
          commit(types.SET_OFFORONLINE_STATUS, { _id: obj._id, statu: 'online' })
          if (obj.disConnType === 'client namespace disconnect') {
            commit(gtypes.SET_NOTIFY, { tag: 'webchat', notify: obj })
          }
          if (obj.initiating) { // 座席对已关闭会话主动发起会话的提醒
            commit(gtypes.SET_NOTIFY, { tag: 'webchat', notify: obj })
          }
        } else if (obj.operation === 'changePeer' || obj.msgType === 'convertManual') {
          commit(gtypes.SET_NOTIFY, { tag: 'webchat', notify: obj })
        }
        commit(types.UPDATE_PRELOADED_MSG, { message: '', flag: false, _id: obj._id })
        if (evtJson.assign) {
          dispatch('pushQueueNumToWebChatClients', { toPeer: obj.toPeer })
        }
        if (state.webchatList.webchat_todo.init) {
          webchatTodoItemAdd({ commit, state }, obj)
        } else {
          let data = { submenu: 'webchat_todo' }
          dispatch('queryWebchatList', data)
        }
      } else {
        // 消息类型为新的系统消息 并且 类型为 屏幕分享
        if (obj.msgType === 'newSystem' && obj.contentType === 'screenShare') {
          if (state.webchatList.webchat_todo.init) {
            webchatTodoItemAdd({ commit, state }, obj)
          } else {
            let data = { submenu: 'webchat_todo' }
            dispatch('queryWebchatList', data)
          }
          if (obj.screenShareStatus === 'refuse') {
            // 屏幕共享被拒绝
            let msg = {
              status: false,
              id: '',
              name: ''
            }
            this.$store.commit(types.SET_SHARESCREEN, msg)
          }
        } else if (obj.msgType === 'newSystem' && obj.contentType === 'text') {
          webchatTodoItemAdd({ commit, state }, obj)
        }
      }
    }
  }
}

let webchatTodoItemAdd = function ({ commit, state }, dataObj) {
  let data = deepClone(dataObj)
  new Promise(function (resolve) {
    data.sName = data.sName || ' '
    if (data.createTime) {
      let _t = formatShortTime(data.createTime)
      data.shortTime = _t.name
    } else {
      data.shortTime = ''
    }
    if (data.msgType === 'newConn') {
      let strarr = data.createTime.split(' ')
      data.message = strarr[1] + ' ' + m7Language('webchat.newCon')
      data.type = 'system'
    } else if (data.msgType === 'disConn') {
      let strarr = data.createTime.split(' ')
      data.message = strarr[1] + ' ' + m7Language('webchat.disCon')
      data.type = 'system'
    } else if (data.msgType === 'invited') {
      data.message = '邀请' + data.invitedUserName + m7Language('webchat.invited')
      data.type = 'system'
    } else if (data.msgType === 'invite_accept') {
      data.message = '座席' + data.invitedUserName + m7Language('webchat.inviteAccept')
      data.type = 'system'
    } else if (data.msgType === 'invite_quit') {
      data.message = '座席' + data.invitedUserName + m7Language('webchat.inviteExit')
      data.type = 'system'
    } else if (data.msgType === 'invite_refuesd') {
      data.message = '座席' + data.invitedUserName + m7Language('webchat.inviteRefuesd')
      data.type = 'system'
    } else if (data.msgType === 'invite_cancel') {
      data.message = m7Language('webchat.inviteCancel1') + data.invitedUserName + m7Language('webchat.inviteCancel2')
      data.type = 'system'
    } else if (data.msgType === 'invite_kick') {
      data.message = m7Language('webchat.inviteKick1') + data.invitedUserName + m7Language('webchat.inviteKick2')
      data.type = 'system'
    } else if (data.msgType === 'saveImCSRInfo') {
      data.createTime = data.createTime
      if (data.platform !== 'pc' && data.isInvestigate !== undefined && !data.isInvestigate) { // 已经评价过了
        return
      }
      data.message = data.message
      data.type = 'system'
      /* } */
    } else if (data.msgType === 'groupMsg') {
      data.type = 'out'
      data.message = data.content
      if (data.username) {
        Vue.set(data, 'uidDesc', data.username)
      }
    } else { // newMsg ,investigate
      if (data.contentType !== 'video') {
        data.message = data.content
      }
    }
    if (data.contentType) {
      if (data.createTime) {
        data.dateTime = data.createTime
        data.showTime = data.createTime
      } else if (data.dateTime) {
        data.showTime = data.dateTime
      }
    }
    // syncOtherClient pc和app 同时登陆，app发送消息推送类型
    if (data.msgType === 'newMsg' || data.msgType === 'newConn' || data.msgType === 'sendImQAMsg' || data.msgType === 'newSystem' || data.msgType === 'syncOtherClient') {
      if (data.userStatus && data.userStatus === 'offline') {
        Vue.set(data, 'userStatus', 'offline')
        Vue.set(data, 'userStatusClass', 'nonline')
        let strNew = '离线 ' + data.shortTime
        Vue.set(data, 'userStatusDesc', strNew)
      } else {
        Vue.set(data, 'userStatus', 'online')
        Vue.set(data, 'userStatusClass', 'online')
        Vue.set(data, 'userStatusDesc', '在线')
      }
      if (data.msgType === 'newSystem') {
        Vue.set(data, 'uidDesc', '系统')
      } else if (data.msgType === 'syncOtherClient') {
        Vue.set(data, 'uidDesc', m7Language('public.myselfI'))
        webchatHourMeter({ commit, state }, {
          startWaitTimer: -1,
          online: 'online',
          sessionId: data._id
        })
      }
    }
    if (data.msgType === 'disConn') {
      Vue.set(data, 'userStatus', 'offline')
      Vue.set(data, 'userStatusClass', 'nonline')
      let strNew = '离线 ' + data.shortTime
      Vue.set(data, 'userStatusDesc', strNew)
      if (data.disConnType === 'client namespace disconnect') {
        removeTimer({ commit, state }, data._id)
      }
    }
    if (data.status !== 'finish' && data.msgType !== 'disConn') {
      if (data.userStatus === 'offline') {
        Vue.set(data, 'userStatus', 'offline')
        Vue.set(data, 'userStatusClass', 'nonline')
        let offlineTime = getFormatDateTime(new Date(data.sBreakTime))
        let strNew = '离线 ' + formatShortTime(offlineTime)
        Vue.set(data, 'userStatusDesc', strNew)
        removeTimer({ commit, state }, data._id)
      } else if (data.userStatus === 'online') {
        Vue.set(data, 'userStatus', 'online')
        Vue.set(data, 'userStatusClass', 'online')
        Vue.set(data, 'userStatusDesc', '在线')
      }
    }
    if (data.type === 'changePeer') {
      Vue.set(data, 'contentType', 'text')
      Vue.set(data, 'type', 'out')
      Vue.set(data, 'userStatus', '')
      Vue.set(data, 'userStatusClass', '')
      Vue.set(data, 'userStatusDesc', '')
      // sdk渠道的会话，在转接的时候，需要去掉访客等待时长
      if (data.platform = 'sdk') {
        removeTimer({ commit, state }, data._id)
      }
    }
    Vue.set(data, 'type', data.type || 'in')
    Vue.set(data, 'leakNum', data.leakNum || 0)
    Vue.set(data, 'status', data.status || 'deal')
    let isEsc = false
    if (data.contentType === 'text') {
      if (data.showHtml === true || data.showHtml === 'true') {
        isEsc = true
      }
    }
    Vue.set(data, 'message', data.message === 'undefined' ? '' : data.message)
    Vue.set(data, 'message', renderEmoji(data.message, isEsc))
    if (data.contentType === 'text') {
      Vue.set(data, 'contentHasUrl', '')
      let oldContent = data.message
      let contentNew = msgConvertion(data.message)
      Vue.set(data, 'message', contentNew)
      if (oldContent !== contentNew) {
        Vue.set(data, 'contentHasUrl', 'have')
      }
    }
    if (data.contentType === 'file') {
      // Vue.set(data, 'fileName', transferFileContent(data.message))
      if (data.platform === 'wxkf') {
        Vue.set(data, 'fileName', transferWxkfFileContent(data.message))
      } else {
        Vue.set(data, 'fileName', transferFileContent(data.message))
      }
      Vue.set(data, 'mp3Suffix', checkSuffix(data.fileName, 'mp3,wav,ogg'))
      if (data.mp3Suffix) {
        Vue.set(data, 'play', false)
      }
    } else if (data.contentType === 'voice') {
      Vue.set(data, 'play', false)
    }
    if (data.contentType === 'video' && state.isinviteVideo && data.videoStatus === 'cancel') {
      // 视频聊天邀请被取消
      commit(types.UPDATE_VIDEO_INVITE_STATUS, false)
      let inviteMsg = {
        videoInviteSessionid: '',
        videoInviteToken: '',
        roomId: '',
        videoType: '',
        password: ''
      }
      commit(types.UPDATE_VIDEO_INVITE_DATA, inviteMsg)
    }
    if (data.contentType === 'video' && state.isVideoing && data.videoStatus === 'refuse') {
      // 视频邀请被对方拒绝
      if (data.refuseReason) {
        let refuseTip = 'webchat.' + data.refuseReason
        commit(gtypes.SET_ERROR, refuseTip)
      }
      commit(types.UPDATE_VIDEO_CHAT_STATUS, false)
      let videoMsg = {
        videoSessionid: '',
        videoToken: '',
        videoUsername: '',
        videoSource: ''
      }
      commit(types.UPDATE_VIDEO_CHATDATA, videoMsg)
    }
    if (data.contentType === 'video' && (data.videoStatus === 'Hangup' || data.videoStatus === 'hangup')) {
      // 视频聊天正常挂断结束
      // webchatCard更新 showVideoIcon状态
      let showVideoIconMsg = {
        videoSessionid: data._id
      }
      commit(types.UPDATE_SHOWVIDEOICON, showVideoIconMsg)
    }
    if (data.contentType === 'video' && state.isVideoing && (data.videoStatus === 'Hangup' || data.videoStatus === 'hangup')) {
      // 视频聊天对方正常挂断结束
      // 重置视频状态，关闭视频窗口
      commit(types.UPDATE_VIDEO_CHAT_STATUS, false)
      let videoMsg = {
        videoSessionid: '',
        videoToken: '',
        videoUsername: '',
        videoSource: ''
      }
      commit(types.UPDATE_VIDEO_CHATDATA, videoMsg)
    }
    if (data.contentType === 'video' && data.type === 'out') {
      removeTimer({ commit, state }, data.sessionId)
    }
    if (data.type === 'in' && data.contentType === 'video' && !data.isAgentLastReply) {
      webchatHourMeter({ commit, state }, {
        startWaitTimer: -1,
        online: 'online',
        sessionId: data._id
      })
    }
    if (data.contentType === 'screenShare' && !data.isAgentLastReply) {
      webchatHourMeter({ commit, state }, {
        startWaitTimer: -1,
        online: 'online',
        sessionId: data._id
      })
    }
    if (data.contentType === 'sessionFormSubmit') {
      data.content = m7Language('webchat.sessionFormTip', { name: '表单' })
      data.type = 'sessionFormSubmit'
    }
    //  在线咨询右侧扩展字段实时变化更新
    if (data.msgType === 'newConn' && data.otherParams) {
      commit(types.UPDATE_WEBCHAT_OTHER_PARAMS, data)
    }
    commit(types.UPDATE_WEBCHAT_MESSAGE_LIST, data)
    resolve()
  }).then(() => {
    if (state.load) {
      if (data.contentType === 'text' && data.user !== 'system' && data.user !== 'robot') {
        autoMatchMsg({ commit, state }, { message: data.message, sessionId: data._id, flag: 'new' })
      }
      if (data.startWaitTimer > -1 && !data.isAgentLastReply && data.msgType === 'newMsg') {
        webchatHourMeter({ commit, state }, {
          startWaitTimer: data.startWaitTimer,
          online: data.userStatus,
          sessionId: data._id
        })
      } else if (data.startWaitTimer > -1 && data.lastMessageFrom === 'customer' && data.operation === 'redirect') {
        webchatHourMeter({ commit, state }, {
          startWaitTimer: data.startWaitTimer,
          online: data.userStatus,
          sessionId: data._id
        })
      } else {
        if (data.type === 'in' && data.when) {
          if (data.userStatus === 'online' && !data.isAgentLastReply && data.msgType === 'newMsg') {
            webchatHourMeter({ commit, state }, {
              startWaitTimer: data.startWaitTimer,
              online: 'online',
              sessionId: data._id
            })
          }
        }
      }
      if (state.current.webchat_todo.currentOpenSession === data._id && document.getElementsByClassName('webchat_todo_conbox').length) {
        dealMsg({ commit }, { tabType: 'webchat_todo', _id: data._id })
      }
      commit(types.SORTLISTBY_TYPE)
    }
  })
}

export const changeStatus = ({ commit, state, rootState }, data) => {
  let sessionId = data.ubaSessionId
  let ubaSession = state.inviteUbaSessionList.list.filter(obj => obj._id === sessionId)[0]
  if (ubaSession) {
    if (ubaSession.status !== 'webchat.inviteStatusTypingTable' && ubaSession.status !== 'webchat.inviteStatusSuccess' && data.msgType === 'typeNotice') {
      let oldVal = ubaSession.status
      let status = 'webchat.inviteStatusTypingTable'
      ubaSession.status = status
      ubaSession.dis_click = true
      setTimeout(() => {
        if (ubaSession.status !== 'webchat.inviteStatusSuccess') {
          status = oldVal
          ubaSession.status = status
          ubaSession.dis_click = true
        }
      }, 5000)
    } else if (data.msgType === 'newMsg') {
      let status = 'webchat.inviteStatusSuccess'
      ubaSession.status = status
      ubaSession.dis_click = true
    }
  }
}

export const dispatchUba = ({ commit, state, rootState, dispatch }, evtJson) => {
  let obj = evtJson.Data
  if (obj.type === 'newUbaInfo') {
    let page = obj.page
    let pageId = page.id
    let ubaSessionId = obj.ubaSessionId
    // let ubaSession = state.ubaInfoList[ubaSessionId]
    // let ubaSession = state.current.webchat_todo.ubaInfoList[ubaSessionId]
    let ubaSession = state.ubaInfoListAll[ubaSessionId]
    console.log(ubaSession)
    if (ubaSession && ubaSession.pages && ubaSession.pages.length > 0) {
      let data = {}
      let stayTimeDesc = ''
      let hasPage = ubaSession.pages.filter(obj => obj._id === pageId)[0]
      if (page.stayTime) {
        let stayTime = userStayTimeConverse(page.stayTime)
        if (!stayTime) {
          stayTime = '0秒'
        }
        stayTimeDesc = '停' + stayTime
        if (typeof (hasPage) !== 'undefined') {
          commit(types.UBAINFO_PUSH, { _id: pageId, stayTimeDesc: stayTimeDesc, sessionId: ubaSessionId, change: true })
        } else {
          for (let key in page) {
            data[key] = page[key]
          }
          data._id = data.id
          data.account = obj.account
          data.sessionId = obj.ubaSessionId
          data.userId = obj.ubaUserId
          data.isStartPage = false
          data.sessionId = obj.ubaSessionId
          data.timeStart = getFormatDateTime(new Date(data.timeStart)).split(' ')[1]
          data.stayTimeDesc = stayTimeDesc
          commit(types.UBAINFO_PUSH, data)
        }
      } else {
        // 新添加
        if (typeof (hasPage) === 'undefined') {
          for (let key in page) {
            data[key] = page[key]
          }
          data._id = data.id
          data._id = data.id
          data.account = obj.account
          data.sessionId = obj.ubaSessionId
          data.userId = obj.ubaUserId
          data.isStartPage = false
          data.sessionId = obj.ubaSessionId
          data.timeStart = getFormatDateTime(new Date(data.timeStart)).split(' ')[1]
          commit(types.UBAINFO_PUSH, data)
        }
      }
    }
  }
}

export const getMatchMsgResponse = ({ commit, state }, { data, sid }) => {
  if (!data.phone && !data.displayName && !data.importSid) {
    return
  }
  return new Promise(function (resolve) {
    customer.queryCustomerByPopupNew(data)
      .then(
        response => {
          response.count = response.list
          let info = {
            autoCustName: state.autoCust[sid].autoCustName,
            autoCustPhone: state.autoCust[sid].autoCustPhone,
            autoContectPerson: state.autoCust[sid].autoContectPerson,
            autoMatchContent: state.autoCust[sid].autoMatchContent,
            autoMatchType: state.autoCust[sid].autoMatchType,
            autoCustObj: response,
            autoCustLength: response.list.length || 0,
            importSid: data.importSid || ''
          }
          commit(types.AUTO_CUST_INFO, { sessionId: sid, data: info })
          resolve()
        }
      ).catch(() => {
        // 'message.default_tips'
      })
  })
}
export const autoMatchMsg = ({ commit, state }, { message, sessionId, flag }) => {
  console.log('autoMatchMsg: ' + message)
  return new Promise(function (resolve) {
    let messageNew = deepClone(message)
    messageNew = messageNew.replace(/<label7moor>/ig, '').replace(/<\/label7moor>/g, '')
    messageNew = messageNew.replace(/<[^>]+>/g, '  ')
    let regName = /[\s,.?;!:、，。？；！： ]+(.*(先生|小姐|女士|男士|有限公司))/gm
    let regName2 = /(.*(先生|小姐|女士|男士|有限公司))/gm
    let regPhone = /((\d{11,12})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)/gm
    let ary
    let useName = true
    let usePhone = true
    let request = false
    let info
    if (state.autoCust[sessionId]) {
      info = {
        autoCustName: state.autoCust[sessionId].autoCustName,
        autoCustPhone: state.autoCust[sessionId].autoCustPhone,
        autoContectPerson: state.autoCust[sessionId].autoContectPerson,
        autoCustLength: state.autoCust[sessionId].autoCustLength,
        autoCustObj: state.autoCust[sessionId].autoCustObj,
        autoMatchContent: state.autoCust[sessionId].autoMatchContent,
        autoMatchType: state.autoCust[sessionId].autoMatchType
      }
    } else {
      info = {
        autoCustName: '',
        autoCustPhone: '',
        autoContectPerson: '',
        autoCustLength: 0,
        autoCustObj: {},
        autoMatchContent: '',
        autoMatchType: ''
      }
    }
    if (flag === 'new') {
      ary = regName.exec(messageNew)
    } else {
      if (info.autoCustName) {
        useName = false
      }
      if (info.autoCustPhone) {
        usePhone = false
      }
      if (info.autoCustName && info.autoCustPhone) {
        resolve()
        return
      }
      if (useName) {
        ary = regName.exec(messageNew)
      }
    }
    let data = {}
    if (ary && ary.length > 0) {
      info.autoCustName = data.displayName = RegExp.$1
      if (info.autoMatchType !== 'phone' && info.autoMatchType !== 'userset') {
        info.autoMatchContent = info.autoCustName
        info.autoMatchType = 'name'
      }
      request = true
    } else if (useName) {
      let _ary = regName2.exec(messageNew)
      if (_ary && _ary.length > 0) {
        info.autoCustName = data.displayName = RegExp.$1
        if (info.autoMatchType !== 'phone' && info.autoMatchType !== 'userset') {
          info.autoMatchContent = info.autoCustName
          info.autoMatchType = 'name'
        }
        request = true
      }
    }
    let ary1 = []
    let messagePhone = messageNew.replace(/<[^>]+>/g, ' ')
    //  屏蔽掉html标签是因为webim的sessionId有可能会出现11位的长数字导致自动定位到客户
    if (usePhone) {
      ary1 = regPhone.exec(messagePhone)
    }
    if (ary1 && ary1.length > 0) {
      info.autoCustPhone = data.phone = ary1[0]
      info.autoMatchContent = info.autoCustPhone
      info.autoMatchType = 'phone'
      request = true
    }
    if (info.autoCustName && info.autoCustPhone) {
      data.field = 'webchat'
      data.phone = info.autoCustPhone
      data.displayName = info.autoCustName
    }
    if (request) {
      if (state.autoCust[sessionId]) {
        data.importSid = state.autoCust[sessionId].importSid || ''
      } else {
        data.importSid = ''
      }

      data.displayName = info.autoMatchContent
      data.phone = info.autoMatchContent

      commit(types.AUTO_CUST_INFO, { sessionId: sessionId, data: info })
      getMatchMsgResponse({ commit, state }, { data: data, sid: sessionId }).then(() => {
        resolve()
      })
    } else {
      resolve()
    }
  })
}
let webchatHourMeter = function ({ commit, state }, { startWaitTimer, online, sessionId }) {
  console.log(startWaitTimer, sessionId, online)
  if (startWaitTimer > -1 && online === 'online') {
    commit(types.UPDATE_STARTWAITTIMER, { startWaitTimer: startWaitTimer, sessionId: sessionId })
  } else {
    if (startWaitTimer === -1) {
      removeTimer({ commit, state }, sessionId)
    }
  }
}

let removeTimer = function ({ commit, state }, sessionId) {
  commit(types.UPDATE_STARTWAITTIMER, { startWaitTimer: -1, sessionId: sessionId })
}

let removeTodoItem = function ({ commit, state }, sessionId) {
  commit(types.REMOVE_SESSION, sessionId)
  commit(types.SORTLISTBY_TYPE)
  removeTimer({ commit, state }, sessionId)
}
/**
 * 获取会话邀请会话列表
 * @param commit
 * @param rootState
 * @param dispatch
 * @param data
 * @param data.pageSize 条数
 * @returns {Promise.<T>|Promise<R>}
 */
export const getSessionsByAccount = ({ commit, state, rootState, dispatch }, data) => {
  return webchat.getSessionsByAccount({
    account: rootState.session.user.account,
    pageSize: data.pageSize,
    page: data.page,
    tableList: data.tableList,
    page_pageSize: 100
  }).then(res => {
    if (res.success) {
      let sessions = res.sessions
      let tabList = res.tableList
      for (let i = 0; i < sessions.length; i++) {
        let _data = sessions[i]
        if (_data.platform.seokeywords === undefined || _data.platform.seokeywords === 'undefined') {
          _data.platform.seokeywords = ''
        }
        let pages = _data.pages
        let pageCreateTime = pages[0].timeStart
        for (let j = 0; j < pages.length; j++) {
          if (pages[j].timeStart > pageCreateTime) {
            pageCreateTime = pages[j].timeStart
          }
          pages[j].stayTime = pages[j].stayTime || ''
          if (pages[j].stayTime) {
            pages[j].stayTime = userStayTimeConverse(pages[j].stayTime)
          }
          pages[j].timeStart = getFormatDateTime(new Date(pages[j].timeStart)).split(' ')[1]
        }
        _data.pageCreateTime = pageCreateTime
        _data.num = (data.page - 1) * data.pageSize + i + 1
        _data.status = 'webchat.inviteStatusStaying'
        _data.page = 1
      }
      state.inviteUbaSessionList.list = sessions
      state.inviteUbaSessionList.tableList = tabList
    }
    return res
  }).catch(err => {
    console.log(err)
    // 'message.default_tips'
  })
}
/**
 * 邀请会话敏感词
 * @param commit
 * @param state
 * @param rootState
 * @param dispatch
 * @param data
 * @param data.content: //邀请词
 * @returns {*|Promise<R2|R1>|Promise<R>|Promise.<TResult>}
 */
export const inviteCustomersSensitiveWords = ({ commit, state, rootState, dispatch }, data) => {
  return webchat.inviteCustomersSensitiveWords(data).then(res => {
    if (res.success) {
      return res
    } else {
      commit(gtypes.SET_ERROR, 'webchat.illegal')
    }
  }).catch(err => {
    console.log(err)
    // 'message.default_tips'
  })
}
/**
 * 邀请会话
 * @param commit
 * @param state
 * @param rootState
 * @param dispatch
 * @param data
 * @param data.sessionIds //要邀请的轨迹会话id
 * @param data.inviteMessage //邀请语
 * @returns {*|Promise<R2|R1>|Promise<R>|Promise.<TResult>}
 */
export const inviteCustomers = ({ commit, state, rootState, dispatch }, data) => {
  return webchat.inviteCustomers({
    agentId: rootState.session.sessionId,
    sessionIds: data.sessionIds,
    account: rootState.session.user.account,
    inviteMessage: data.inviteMessage
  }).then(res => {
    if (res.success) {
      let rsList = data
      if (rsList.length) {
        for (var i = 0; i < rsList.length; i++) {
          let rsLi = rsList[i]
          let ubaSession = state.inviteUbaSessionList.list.filter(obj => obj._id === rsLi.sessionId)[0]
          if (rsLi.success) {
            ubaSession.status = 'webchat.inviteStatusInviting'  // 正在邀请
          } else {
            if (rsLi.message === 'haveInvited') {
              ubaSession.status = 'webchat.inviteStatusHaveInvited' // 已被邀请
            }
            if (rsLi.message === 'offline') {
              ubaSession.status = 'webchat.inviteStatusOffline'   // 关闭页面
            }
            if (rsLi.message === 'haveSession') {
              ubaSession.status = 'webchat.inviteStatusHaveSession'  // 已有会话
            }
            if (rsLi.message === 'blackUser') {
              ubaSession.status = 'webchat.inviteStatusBlackUser'  // 已被封禁
            }
          }
          ubaSession.dis_click = true
        }
      }
    }
    return res
  }).catch(err => {
    console.log(err)
    // 'message.default_tips'
  })
}

/**
 * 加载浏览轨迹
 * @param commit
 * @param state
 * @param rootState
 * @param dispatch
 * @param data
 * @param data._id
 * @returns {Promise.<T>|Promise<R>}
 */
export const loadUbaInfo = ({ commit, state, rootState, dispatch }, data) => {
  let _id = data._id
  let ubaSessionId = data.ubaSessionId
  let wSesssion = ''
  if (data.tabType === 'webchat_todo') {
    wSesssion = state.current.webchat_todo.currentSession[_id]
  } else if (data.tabType === 'webchat_queue' || data.tabType === 'webchat_all' || data.tabType === 'webchat_robot' || data.tabType === 'webchat_laterProcess') {
    wSesssion = state.current[data.tabType].currentSession
  }
  let reqData = { pageSize: 100, account: rootState.session.account.account }
  if (wSesssion && wSesssion.ubaInfo) {
    reqData.ubaSessionId = wSesssion.ubaInfo.ubaSessionId
    reqData.ubaPageId = wSesssion.ubaInfo.ubaPageId
  }
  if (data.ubaPageId && data.ubaSessionId) {
    reqData.ubaSessionId = data.ubaSessionId
    reqData.ubaPageId = data.ubaPageId
  }
  let ubaInfo = state.ubaInfoList[ubaSessionId]
  let commitData = { _id: _id }
  if (ubaInfo && !data.ubaHistory) {
    reqData.page = ubaInfo.page + 1
    reqData.timeStart = ubaInfo.lastPageTimeStart
    let ubaInfo = state.ubaInfoList[reqData.ubaSessionId]
    if (ubaInfo) {
      ubaInfo.page = ubaInfo.page + 1
      ubaInfo.pages = state.ubaInfoListAll[reqData.ubaSessionId].pages.slice(0, (ubaInfo.page + 1) * 10)
    }
    return reqData.ubaSessionId
  } else if (data.currentPage) {
    reqData.page = data.currentPage
    reqData.timeStart = ''
    let ubaInfo = state.ubaInfoList[reqData.ubaSessionId]
    if (ubaInfo) {
      ubaInfo.page = data.currentPage
      ubaInfo.pages = state.ubaInfoListAll[reqData.ubaSessionId].pages.slice(0, data.currentPage * 10)
    }
    return reqData.ubaSessionId
  } else {
    reqData.page = 1
    commitData.page = 1
    reqData.timeStart = ''
  }

  return webchat.getUbaPagesBySessionIdForWebchat(reqData).then(response => {
    if (response.success) {
      let page = response.data.page || []
      if (page.length) {
        let lastPageTimeStart = page[0].timeStart
        for (let i = 0; i < page.length; i++) {
          let _data = page[i]
          if (page[i].timeStart > lastPageTimeStart) {
            lastPageTimeStart = page[i].timeStart
          }
          if (_data.stayTime) {
            _data.stayTimeDesc = '停' + userStayTimeConverse(_data.stayTime)
          }
          _data.timeStart = getFormatDateTime(new Date(page[i].timeStart)).split(' ')[1]
          if (page[i]._id === reqData.ubaPageId) {
            page[i].isStartPage = true
          } else {
            page[i].isStartPage = false
          }
        }
        if (!ubaInfo) {
          commitData.lastPageTimeStart = lastPageTimeStart
        }
        commitData.pages = page
        commitData.sessionId = response.data.sessionId
        commit(types.UBAINFO, commitData)
        return commitData.sessionId
      }
    }
  }).catch(err => {
    console.log(err)
    // 'message.default_tips'
  })
}

/**
 * 将访客加入黑名单
 * @param commit
 * @param state
 * @param data
 */
export const customerAddBlack = ({ commit, state }, data) => {
  let reqData = {}
  let currentInfo = state.current.webchat_todo.currentSession[data._id]
  reqData._id = data.sid
  reqData.addBlackReason = data.addBlackReason
  reqData.ip = currentInfo.ip
  reqData.area = currentInfo.area
  reqData.sName = currentInfo.sName
  if (data.type) {
    reqData.type = data.type
  }
  return webchat.addBlack(reqData).then((res) => {
    if (res.success) {
      commit(gtypes.SET_SUCCESS, m7Language('webchat.addBlackSuccess'))
    }
    return res
  }).catch(err => {
    console.log(err)
    // 'message.default_tips'
  })
}

export const updateCurrentWebchatListCustomer = ({ commit }, data) => {
  commit(types.UPDATE_WEBCHAT_RELATION_CUSTOMER, data)
}

/**
 * 更新时间检索状态
 */
export const updateTimeSearchState = ({ commit }, data) => {
  commit(types.UPDATE_TIME_SEARCH_STATE, data)
}
export const getClackInfo = ({ commit, rootState, state }, data) => {
  let clackInfo = m7dicMap.getCache('clackInfo')
  // let clackSecretId = rootState.session.dicMap.clackInfo[0].code_value.clackSecretId
  // let clackSecretKey = rootState.session.dicMap.clackInfo[0].code_value.clackSecretKey
  let clackSecretId = clackInfo[0].code_value.clackSecretId
  let clackSecretKey = clackInfo[0].code_value.clackSecretKey
  let authorization = Base64.encode(clackSecretId + ':' + getFormatDateTime(new Date(), true))
  let sig = md5(clackSecretId + clackSecretKey + getFormatDateTime(new Date(), true)).toUpperCase()
  let movieId = data.id
  data.authorization = authorization
  data.sig = sig
  if (data.name === 'frames' && trackVideoStore[movieId]) {
    return trackVideoStore[movieId]
  } else {
    return webchat.getClackInfo(data).then((res) => {
      if (res && res.length) {
        if (data.name === 'movies') {
          state.trackMovie.movieList = res
        } else if (data.name === 'frames') {
          trackVideoStore[movieId] = res
        }
        return res
      }
    }).catch(err => {
      console.log(err)
      // 'message.default_tips'
    })
  }
}

export const getChildrenInfo = ({ commit, rootState, state }, data) => { // 获取children列表 进行页面的初始化
  let clackInfo = m7dicMap.getCache('clackInfo')
  // let clackSecretId = rootState.session.dicMap.clackInfo[0].code_value.clackSecretId
  // let clackSecretKey = rootState.session.dicMap.clackInfo[0].code_value.clackSecretKey
  let clackSecretId = clackInfo[0].code_value.clackSecretId
  let clackSecretKey = clackInfo[0].code_value.clackSecretKey
  let authorization = Base64.encode(clackSecretId + ':' + getFormatDateTime(new Date(), true))
  let sig = md5(clackSecretId + clackSecretKey + getFormatDateTime(new Date(), true)).toUpperCase()
  data.authorization = authorization
  data.sig = sig
  return webchat.getClackInfo(data).then((res) => {
    if (res && res.children) {
      return res.children
    }
  }).catch(err => {
    console.log(err)
  })
}

let getClackFrameArr = []
export const getClackFrameInfo = ({ commit, dispatch, rootState, state }, data) => { // 多线程获取frames
  getClackFrameArr = []
  let clackInfo = m7dicMap.getCache('clackInfo')
  // let clackSecretId = rootState.session.dicMap.clackInfo[0].code_value.clackSecretId
  // let clackSecretKey = rootState.session.dicMap.clackInfo[0].code_value.clackSecretKey
  let clackSecretId = clackInfo[0].code_value.clackSecretId
  let clackSecretKey = clackInfo[0].code_value.clackSecretKey
  let authorization = Base64.encode(clackSecretId + ':' + getFormatDateTime(new Date(), true))
  let sig = md5(clackSecretId + clackSecretKey + getFormatDateTime(new Date(), true)).toUpperCase()
  data.authorization = authorization
  data.sig = sig
  let allSkip = Math.ceil(data.frameCount / data.pageSize)
  let p = []
  for (let i = 0; i < allSkip; i++) {
    data.skip = data.pageSize * i
    data.limit = data.pageSize * (i + 1) - 1
    data.Index = i
    p[i] = dispatch('getClackFrameInfoFn', data)
  }
  return Promise.all(p).then(() => {
    getClackFrameArr.sort((x, y) => { // 获取frames后进行排序
      return x.index > y.index ? 1 : -1
    })
    console.log(getClackFrameArr)
    let framesArr = []
    getClackFrameArr.forEach((item, index) => {
      framesArr = framesArr.concat(item[index])
    })
    return framesArr
  })
}

export const getClackFrameInfoFn = ({ commit, rootState, state }, data) => {
  let index = data.Index
  return webchat.getClackInfo(data).then((res) => {
    if (res && res.length) {
      let obj = {}
      obj[index] = res
      obj.index = index
      getClackFrameArr.push(obj)
      return res
    }
  }).catch(err => {
    console.log(err)
  })
}
export const dealImMsgFromUser = ({ commit, rootState, state }, data) => {
  return webchat.dealImMsgFromUser(data).then((res) => {
    if (res && res.success) {
      commit('UPDATELASTMESSAGE', { _id: data.sessionId })
    }
  }).catch(err => {
    console.log(err)
  })
}
export const clearTrackVideoStore = ({ state, dispatch }) => {
  trackVideoStore = {}
}

// ----------------------- movie ----------------------- //

export const startMovie = ({ commit }) => {
  commit(types.START_MOVIE)
}

export const stopMovie = ({ commit }) => {
  commit(types.STOP_MOVIE)
}

export const initPlayer = ({ commit }, movies) => {
  try {
    const player = new Player({
      target: document.getElementById('player-iframe')
    })
    commit(types.INIT_PLAYER, {
      err: null,
      data: player
    })
  } catch (e) {
    commit(types.INIT_PLAYER, {
      err: e,
      data: null
    })
  }
}

export const updatePlaySpeed = ({ commit }, speed) => {
  commit(types.UPDATE_PLAY_SPEED, {
    err: null,
    data: speed
  })
}

export const updateCurrentMovie = ({ commit }, movie) => {
  commit(types.UPDATE_CURRENT_MOVIE, {
    err: null,
    data: movie
  })
}

/**
 * 接受视频邀请
 * @param data
 * */
export const acceptVideoInvite = ({ commit }, data) => {
  return webchat.acceptVideoInvite(data)
    .then(
      response => {
        if (response.success) {
          commit(types.UPDATE_VIDEO_INVITE_STATUS, false)
        }
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 拒绝视频邀请
 * @param data
 * */
export const rejectVideoInvite = ({ commit }, data) => {
  return webchat.rejectVideoInvite(data)
    .then(
      response => {
        if (response.success) {
          commit(types.UPDATE_VIDEO_INVITE_STATUS, false)
        }
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 取消视频邀请
 * @param data
 * */
export const cancelVideoInvite = ({ commit }, data) => {
  return webchat.cancelVideoInvite(data)
    .then(
      response => {
        if (response.success) {
          commit(types.UPDATE_VIDEO_CHAT_STATUS, false)
          let msg = {
            videoSessionid: '',
            videoToken: '',
            videoUsername: '',
            videoSource: ''
          }
          commit(types.UPDATE_VIDEO_CHATDATA, msg)
        }
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 座席请求视频聊天
 * @param data
 * */
export const requestVideoChat = ({ commit }, data) => {
  return webchat.requestVideoChat(data)
    .then(
      response => {
        if (response.success) {
          commit(types.UPDATE_VIDEO_CHAT_STATUS, true)
          let msg = {
            videoSessionid: data.sessionId,
            videoToken: response.token,
            videoUsername: data.sName,
            videoSource: 'initiative',
            roomId: response.roomId,
            password: response.password
          }
          commit(types.UPDATE_VIDEO_CHATDATA, msg)
        }
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 获取当前座席是否存在正在视频会话数
 * @param data
 * */
export const getAgentVedioRelation = ({ commit }, data) => {
  return webchat.getAgentVedioRelation(data)
    .then(
      response => {
        if (response.success) {
          return response
        }
      }
    ).catch(() => { })
}
/**
 * 座席请求视频聊天
 * @param data
 * */
export const remoAgentVedioRelation = ({ commit }, data) => {
  return webchat.remoAgentVedioRelation(data)
    .then(
      response => {
        return response
      }
    ).catch(() => { })
}
/**
* 查询视频回放播放地址
* @param data
 *data._id messageId 消息Id
 *data.sid 访客id
* */
export const queryVideoReplayUrl = ({ commit }, data) => {
  return webchat.queryVideoReplayUrl(data)
    .then(
      response => {
        if (response.success) {
          return response
        }
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}

export const judgeMobileClient = ({ commit }, data) => {
  return webchat.judgeMobileClient(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}

export const closeMobileClaimWebchatSession = ({ commit }, data) => {
  return webchat.closeMobileClaimWebchatSession(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
export const pcInitiativeLogout = ({ commit }, data) => {
  return webchat.pcInitiativeLogout(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
* 获取当前时间和服务器的时间差
* @param data
 *data._id messageId 消息Id
 *data.sid 访客id
* */
export const getServerTimeDiff = ({ commit }, data) => {
  return webchat.getServerTimeDiff(data)
    .then(
      response => {
        if (response.success) {
          return response
        }
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
* 访客消息撤回
* @param data
 *data._id messageId 消息Id
 *data.sid 访客id
* */
export const withdrawMessage = ({ commit }, data) => {
  return webchat.withdrawMessage(data)
    .then(
      response => {
        return response
      }
    ).catch(() => {
      // 'message.default_tips'
    })
}
/**
 * 锁定会话
 * @param data
 *data.sessionId 会话id
 * */
export const webchatLockSession = ({ commit }, data) => {
  return webchat.webchatLockSession(data)
    .then(
      response => {
        return response
      }
    ).catch((error) => {
      console.log(error)
      // 'message.default_tips'
    })
}
/**
 * 解锁会话
 * @param data
 *data.sessionId 会话id
 * */
export const webchatUnlockSession = ({ commit }, data) => {
  return webchat.webchatUnlockSession(data)
    .then(
      response => {
        return response
      }
    ).catch((error) => {
      console.log(error)
      // 'message.default_tips'
    })
}
/**
 * 坐席创建屏幕分享
 ***
 **/
export const creatShareScreen = ({ commit }, data) => {
  return webchat.creatShareScreen(data)
    .then(response => {
      console.log(response)
    })
}
/**
 * 坐席取消或结束屏幕分享
 ***
 **/
export const finishShareScreen = ({ commit }, data) => {
  return webchat.finishShareScreen(data)
    .then(response => {
      console.log(response)
    })
}
/**
 * 坐席开始屏幕分享前更新状态
 * @param data
 * */
export const changeStatusBeforeShare = ({ commit }, data) => {
  return webchat.changeStatusBeforeShare(data)
    .then(response => {
      console.log(response)
    })
}
/**
 * 快捷发送知识库内容时查询富文本信息
 * @param data
 * */
export const getRichTextInfo = ({ commit }, data) => {
  return webchat.getRichTextInfo(data)
    .then(
      response => {
        return response
      }
    ).catch((error) => {
      console.log(error)
      // 'message.default_tips'
    })
}
/**
 * AI智能回答搜索
 * @param data
 * */
export const searchM7AIRobot = ({ commit }, data) => {
  return webchat.searchM7AIRobot(data)
    .then(
      response => {
        return response
      }
    ).catch((error) => {
      console.log(error)
      // 'message.default_tips'
    })
}
/**
 * xbot辅助坐席反馈
 * @param data
 * */
export const humanAssistAccept = ({ commit }, data) => {
  return webchat.humanAssistAccept(data)
    .then(
      response => {
        return response
      }
    ).catch((error) => {
      console.log(error)
      // 'message.default_tips'
    })
}
/**
 * xbot机器人纠错
 * @param data
 * */
export const agentCorrect = ({ commit }, data) => {
  return webchat.agentCorrect(data)
    .then(
      response => {
        return response
      }
    ).catch((error) => {
      console.log(error)
      // 'message.default_tips'
    })
}
/**
 * 正则匹配后缀
 * @param data
 * */
export const checkSuffix = (str, suf) => {
  let strRegex = '(.' + suf.split(',').join('|.') + ')$'
  let re = new RegExp(strRegex)
  if (re.test(str.toLowerCase())) {
    return true
  } else {
    return false
  }
}

/**
 * 座席主动会话
 ***
 **/
export const initiatingWebchat = ({ commit }, data) => {
  return webchat.initiatingWebchat(data)
    .then(response => {
      return response
    })
}
/**
 * 座席获取tab顺序
 ***
 **/
export const getChatTabConfig = ({ commit }, data) => {
  return webchat.getChatTabConfig(data)
    .then(response => {
      if (response.success && response.data && response.data.chatTab) {
        return response.data.chatTab
      } else return []
    })
}
/**
 * 座席更新tab顺序
 ***
 **/
export const updateChatTabConfig = ({ commit }, data) => {
  return webchat.updateChatTabConfig(data)
    .then(response => {
      return response
    })
}
/**
 * 在线咨询添加稍后处理标记
 * @param ids 会话Id数组
 ***
 **/
export const markLaterProcess = ({ commit }, data) => {
  return webchat.markLaterProcess(data)
    .then(response => {
      return response
    })
}
/**
 * 在线咨询取消稍后处理标记
 * @param ids 会话Id数组
 ***
 **/
export const removeLaterProcess = ({ commit }, data) => {
  return webchat.removeLaterProcess(data)
    .then(response => {
      return response
    })
}
/**
 * 在线咨询置顶OR取消置顶会话
 * @param sessionId 会话Id
 * @param sid 访客Id
 * @param status 是否置顶 true/false
 ***
 **/
export const setSessionTop = ({ rootState, commit }, data) => {
  return webchat.setSessionTop(data)
    .then(response => {
      if (response.success) {
        let setTopData = {
          _id: data.sessionId,
          status: data.status,
          userSessionId: rootState.session.sessionId
        }
        commit(types.UPDATE_SETTOP_STATUS, setTopData)
        commit(types.SORTLISTBY_TYPE)
      }
      return response
    })
}
export const webchatVoiceToText = ({ commit }, data) => {
  return webchat.voiceToText(data).then(res => {
    if (res && res.success) {
      return res
    }
  })
}

export const getReadyFinish = ({ commit }, data) => {
  return webchat.getReadyFinish(data).then(res => {
    return res
  })
}

export const updateReadyFinish = ({ commit }, data) => {
  return webchat.updateReadyFinish(data).then(res => {
    return res
  })
}
//  支持座席更新会话的结束标签
export const updateWebchatSessionFinishKey = ({ commit }, data) => {
  return webchat.updateWebchatSessionFinishKey(data).then(res => {
    return res
  })
}
/**
 * 获取在线咨询多域名列表
 * @param page
 * @param limit
 ***
 **/
export const getDomainList = ({ rootState, commit }, data) => {
  return webchat.getDomainList(data)
    .then(response => {
      return response
    })
}
/**
 * 添加在线咨询多域名
 * @param page
 * @param limit
 ***
 **/
export const addDomain = ({ rootState, commit }, data) => {
  return webchat.addDomain(data)
    .then(response => {
      return response
    })
}
/**
 * 更新在线咨询多域名
 * @param page
 * @param limit
 ***
 **/
export const updateDomain = ({ rootState, commit }, data) => {
  return webchat.updateDomain(data)
    .then(response => {
      return response
    })
}
/**
 * 删除在线咨询多域名
 * @param page
 * @param limit
 ***
 **/
export const delDomain = ({ rootState, commit }, data) => {
  return webchat.delDomain(data)
    .then(response => {
      return response
    })
}
/**
 * 添加表情包
 * @param {string} type:类型
 * @param {string} url:表情地址
 */
export const addAgentMeme = ({ rootState, commit }, data) => {
  return webchat.addAgentMeme(data)
    .then(response => {
      return response
    })
}
/**
 * 查找表情包
 * @param {string} limit:每页条数
 * @param {string} page:当前第几页
 */
export const getAgentMeme = ({ rootState, commit }, data) => {
  return webchat.getAgentMeme(data)
    .then(response => {
      return response
    })
}
/**
 * 删除表情包
 * @param {Array}} ids:id数组
 */
export const deleteAgentMeme = ({ rootState, commit }, data) => {
  return webchat.deleteAgentMeme(data)
    .then(response => {
      return response
    })
}
/**
 * 上传消息中获取到的线索
 * @param {Array}} cue:线索字段
 */
export const updateSessionCue = ({ rootState, commit }, data) => {
  return webchat.updateSessionCue(data)
    .then(response => {
      return response
    })
}
/**
 * 主动提交质检
 */
export const commitCheckUp = ({ commit }, data) => {
  return webchat.commitCheckUp(data)
    .then(response => {
      return response
    })
}
/**
 * 主动撤回质检
 */
export const withDrawCheckUp = ({ commit }, data) => {
  return webchat.withDrawCheckUp(data)
    .then(response => {
      return response
    })
}
// 公众号授权获取昵称头像
/**
 *
 */
export const getWeixinVisitorInfoSendMsg = ({ commit }, data) => {
  return webchat.getWeixinVisitorInfoSendMsg(data)
    .then(response => {
      return response
    })
}

